【问题标题】:auto text direction (based on the entered text) in flutter text and text field widgets颤动文本和文本字段小部件中的自动文本方向(基于输入的文本)
【发布时间】:2020-06-20 12:22:31
【问题描述】:

我在 Flutter (ar/en) 中制作多语言应用程序,所以我想用这些语言显示我的内容,我的问题是文本方向基于 ui 语言,我想动态改变方向如果 ar 应该是 rtl,则基于内容,否则 ltr。

我目前的看法 My current view

想要的效果 desired effect

class ArticleCard extends StatelessWidget {
  const ArticleCard({
    Key key,
    @required this.article,
    @required this.isAuthor,
    @required this.onDelete,
    @required this.onEdit,
    this.allowComments = true,
  }) : super(key: key);
  final ArticleModel article;
  final bool isAuthor;
  final bool allowComments;
  final VoidCallback onDelete;
  final VoidCallback onEdit;

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: EdgeInsets.only(bottom: 10),
      child: Column(
        children: <Widget>[
          InkWell(
            onTap: () {
              ExtendedNavigator.ofRouter<Router>().pushNamed(
                Routes.article,
                arguments: ArticleScreenArguments(article: article),
              );
            },
            child: Column(
              children: <Widget>[
                ListTile(
                  leading: CircleAvatar(
                    backgroundImage:
                        CachedNetworkImageProvider(article.owner.avatar),
                  ),
                  title: Text(article.title),
                  subtitle: Text(
                    article.owner.name,
                    textScaleFactor: .75,
                  ),
                  trailing: Text(
                    '${DateFormat('d, MMMM y  h:mm a', 'ar').format(article.createdAt)}',
                    textScaleFactor: .7,
                  ),
                ),
                SizedBox(
                  width: MediaQuery.of(context).size.width,
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 8),
                    child: Text(
                      article.content,
                      textAlign: TextAlign.start,
                    ),
                  ),
                ),
              ],
            ),
          ),
          SizedBox(height: 10),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              FavoriteButton(
                isFavorite: article.isFavorite,
                count: article.favoriteCount,
                type: FavoriteType.article,
                targetId: article.id,
              ),
              _buildLabeledIcon(
                icon: Icon(Icons.message),
                label: '${article.commentsCount}',
              ),
              _buildLabeledIcon(
                icon: Icon(Icons.share),
                label: '${article.shares}',
              ),
              _buildLabeledIcon(
                icon: Icon(Icons.remove_red_eye),
                label: '${article.views}',
              ),
            ],
          ),
          SizedBox(height: 10),
          Container(
            height: 1.5,
            color: Colors.black12,
          ),
          if (isAuthor)
            _buildAuthorRow(),
          // Divider(),
          if (allowComments) ...[
            SizedBox(height: 10),
            _buildCommentsSection(context),
          ]
        ],
      ),
    );
  }

  Row _buildAuthorRow() {
    return Row(
      children: <Widget>[
        Expanded(
          child: InkWell(
            onTap: onEdit,
            child: Container(
              height: 50,
              alignment: Alignment.center,
              child: Text(
                'تعديل',
                style: TextStyle(
                  color: appTheme.accentColor,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ),
        Container(
          width: 1.5,
          height: 50,
          color: Colors.black12,
        ),
        Expanded(
          child: InkWell(
            onTap: onDelete,
            child: Container(
              height: 50,
              alignment: Alignment.center,
              child: Text(
                'حذف',
                style: TextStyle(
                  color: appTheme.errorColor,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  Row _buildLabeledIcon({Widget icon, String label}) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: <Widget>[
        icon,
        SizedBox(width: 5),
        Text(
          label,
          textScaleFactor: .75,
        ),
      ],
    );
  }

  Widget _buildCommentsSection(BuildContext context) {
    return Column(
      children: [
        if (article.comments.isNotEmpty)
          CommentTile(comment: article.comments.first),
        _buildCommentTextInput(context),
      ],
    );
  }

  Widget _buildCommentTextInput(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Row(
        children: <Widget>[
          IconButton(
            icon: Icon(FontAwesomeIcons.paperPlane),
            onPressed: () {},
          ),
          Flexible(
            child: TextField(
              decoration: InputDecoration(
                hintText: 'كتابة تعليق',
                filled: true,
                fillColor: Color(0xFFEFEFEF),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(50)),
                  borderSide: BorderSide.none,
                ),
                contentPadding: EdgeInsets.all(12),
              ),
              onSubmitted: (_) {},
              onTap: () {},
            ),
          ),
        ],
      ),
    );
  }
}

class CommentTile extends StatelessWidget {
  final CommentModel comment;

  const CommentTile({Key key, this.comment}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        ListTile(
          leading: CircleAvatar(
            backgroundImage: CachedNetworkImageProvider(comment.user.avatar),
          ),
          title: Text(comment.user.name),
          subtitle: Text(
            DateFormat.yMEd().format(comment.createdAt),
            textScaleFactor: .75,
          ),
        ),
        SizedBox(
          width: MediaQuery.of(context).size.width,
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 8),
            child: Text(
              comment.text,
              textAlign: TextAlign.end,
            ),
          ),
        ),
      ],
    );
  }
}

【问题讨论】:

    标签: flutter


    【解决方案1】:

    您必须将 intl 包添加到您的项目中,并将此代码用作整个应用的 AppTextField:

    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    import 'package:intl/intl.dart' as intl;
    
    class AppTextField extends StatefulWidget {
      final int maxLines;
      final String title;
      final TextInputType? textInput;
      final bool autoFocus;
      final TextInputAction inputAction;
    
      AppTextField(this.title,
          {this.maxLines: 1,
          this.textInput,
          this.autoFocus: false,
          this.inputAction: TextInputAction.next});
    
      @override
      State<StatefulWidget> createState() => AppTextFieldSate();
    }
    
    class AppTextFieldSate extends State<AppTextField> {
      String? text = '';
    
      bool isRTL(String text) {
        return intl.Bidi.detectRtlDirectionality(text);
      }
    
      @override
      Widget build(BuildContext context) => Container(
          margin: EdgeInsets.symmetric(vertical: 10),
          child: TextField(
              textDirection: isRTL(text!) ? TextDirection.rtl : TextDirection.ltr,
              textInputAction: widget.inputAction,
              keyboardType: widget.textInput,
              autofocus: widget.autoFocus,
              maxLines: widget.maxLines,
              decoration: InputDecoration(
                labelText: widget.title,
              ),
              onChanged: (value) {
                setState(() {
                  text = value;
                });
              }));
    }
    

    希望有用:)

    【讨论】:

      【解决方案2】:
      • 如果您无法检测到应用用户当前使用的语言,您可以尝试firebase ml lnaguage detection kit,它将帮助您检测帖子的语言

      • 根据检测到的语言,您可以设置TexttextAlign 属性 小部件到TextAlign.leftTextAlign.right

      Text("$content", textAlign: lang=='ar'?TextAlign.right:TextAlign.left )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-14
        • 1970-01-01
        • 1970-01-01
        • 2021-11-30
        • 2021-08-10
        • 2015-05-03
        • 2012-11-26
        • 2013-10-09
        相关资源
        最近更新 更多