Как программно выделить слово в строке во флаттере - PullRequest
0 голосов
/ 21 октября 2018

Есть ли способ изменить цвет на конкретное слово в строке?

Text("some long string")

теперь я хочу дать цвет только длинному слову.

может кто-нибудь сказать мне, как я могу сделать это программно?

например: -

Я длинная действительно длинная и длинная строка в некоторой переменной, длинная

Теперь я хочу отделить длинное слово.Я могу отделить простую строку, чтобы выделить одно слово, но не знаю, как найти и выделить каждое из этих слов.

Ответы [ 2 ]

0 голосов
/ 21 октября 2018

это хороший ответ @Gauter Zochbauer.Если Вы хотите изменить динамически, тогда Следуйте за следующим ответом.

import 'package:flutter/material.dart';

void main() => runApp(new MaterialApp(
      title: 'Forms in Flutter',
      home: new LoginPage(),
    ));

class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  Color color =Colors.yellowAccent;

  @override
  Widget build(BuildContext context) {
    final Size screenSize = MediaQuery.of(context).size;

    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Login'),
      ),
      body: new Container(
          padding: new EdgeInsets.all(20.0),
          child: Column(
            children: <Widget>[
              Text.rich(
                TextSpan(
                  text: 'Hello', // default text style
                  children: <TextSpan>[
                    TextSpan(text: ' beautiful ', style: TextStyle(fontStyle: FontStyle.italic,color: color)),
                    TextSpan(text: 'world', style: TextStyle(fontWeight: FontWeight.bold)),
                  ],
                ),
              ),
              new RaisedButton(
                onPressed: (){
                  setState(() {
                    color == Colors.yellowAccent ? color = Colors.red : color = Colors.yellowAccent;
                  });
                },
              child: Text("Click Me!!!")
        ),
            ],
          )
    )); 
  }
}
0 голосов
/ 21 октября 2018

Оберните слово в TextSpan и назначьте style свойства, чтобы изменить внешний вид текста и использовать RichText вместо Text

RichText(
  text: TextSpan(
    text: 'Hello ',
    style: DefaultTextStyle.of(context).style,
    children: <TextSpan>[
      TextSpan(text: 'bold', style: TextStyle(fontWeight: FontWeight.bold)),
      TextSpan(text: ' world!'),
    ],
  ),
)

или используйте конструктор Text.rich https://docs.flutter.io/flutter/widgets/Text-class.html

const Text.rich(
  TextSpan(
    text: 'Hello', // default text style
    children: <TextSpan>[
      TextSpan(text: ' beautiful ', style: TextStyle(fontStyle: FontStyle.italic)),
      TextSpan(text: 'world', style: TextStyle(fontWeight: FontWeight.bold)),
    ],
  ),
)
...