gpt4 book ai didi

flutter 。如何动态更改样式

转载 作者:IT王子 更新时间:2023-10-29 07:14:08 29 4
gpt4 key购买 nike

你好,我是 Flutter 的新手,我的英语很糟糕,但我需要有关动态更改 Widgets 样式的帮助

例如,我想根据 JSON 字段返回的值更改文本颜色。在此示例中,文本是 amberAccent[400],但取决于我想更改为其他的 JSON 字段返回的结果

我可以做一个 if 语句吗?如何?谢谢

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
runApp(new MaterialApp(
home: new HomePage(),
));
}

class HomePage extends StatefulWidget {
@override
HomePageState createState() => new HomePageState();
}

class HomePageState extends State<HomePage> {
List data;

Future<String> getData() async {
var response = await http.get(
Uri.encodeFull("https://jsonplaceholder.typicode.com/posts"),
headers: {"Accept": "application/json"});

this.setState(() {
data = JSON.decode(response.body);
});
print(data[1]["title"]);

return "Success!";
}

@override
void initState() {
this.getData();
}

@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Listviews"),
),
body: new ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index) {
return new MyCard(
title: new Text(data[index]["title"],
style: new TextStyle(
fontSize: 25.0,color: Colors.amberAccent[400]
),),
subtitle: new Text(data[index]["body"],
style: new TextStyle(
fontSize: 10.0,color: Colors.pinkAccent[200]))
);
// return new Card(
// child: new Text(data[index]["title"]),
// );
},
),
);
}
}

class MyCard extends StatelessWidget {
MyCard({this.title, this.subtitle});

final Widget title;
final Widget subtitle;

@override
Widget build(BuildContext context) {
return new Container(
padding: new EdgeInsets.only(bottom: 20.0),
child: new Card(
child: new Container(
padding: new EdgeInsets.all(10.0),
child: new Column(
children: <Widget>[this.title, this.subtitle]))));
}
}

最佳答案

您可以使用 https://flutter.io/cookbook/design/themes/ 中所示的主题

new Theme(
// Create a unique theme with "new ThemeData"
data: new ThemeData(
accentColor: Colors.yellow,
),
child: new FloatingActionButton(
onPressed: () {},
child: new Icon(Icons.add),
),
);

或者在您的示例中 accentColor: Colors.amberAccent[400]

从主题中获取值

new Container(
color: Theme.of(context).accentColor,
child: new Text(
'Text with a background color',
style: Theme.of(context).textTheme.title,
),
);

您可以将其与 StreamBuilder' 或 FutureBuilder` 结合使用以更新主题数据。

您还可以为 Flutter 提供的类未涵盖的属性构建自定义 ThemeThemeData 类。

关于 flutter 。如何动态更改样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49884152/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com