Flutter split and make specific word bold [closed]

蹲街弑〆低调 提交于 2021-01-28 19:09:44

问题


I have string which is like "Hi @username how are you" I want to change @username text to bold... just @username not whole sentence

Example : " Hi @username how are you


回答1:


This is a small function that would do that for you then returns a list of widgets.

List<Text> _transformWord(String word) {
    List<String> name = word.split(' ');
    List<Text> textWidgets = [];
    for (int i = 0; i < name.length; i++) {
      if (name[i].contains('@')) {
        Text bold = Text(
          name[i] + ' ',
          style: TextStyle(
            fontWeight: FontWeight.bold,
          ),
        );
        textWidgets.add(bold);
      } else {
        Text normal = Text(
          name[i] + ' ',
        );
        textWidgets.add(normal);
      }
    }
    return textWidgets;
  }

You would call this function from a row widget

Row(
     children: _transformWord(),
    ),



回答2:


Make use of flutter TextSpan

Text _myText;
/*set _myText.text to whatever text you want */
RichText(
  text: TextSpan(
    text: 'Hi',
    style: DefaultTextStyle.of(context).style,
    children: <TextSpan>[
      TextSpan(text: _myText.text, style: TextStyle(fontWeight: FontWeight.bold)),
      TextSpan(text: 'how are you')




],
  ),
)


来源:https://stackoverflow.com/questions/61252152/flutter-split-and-make-specific-word-bold

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!