您好,我是使用Flutter的新手,我的英语很糟糕,但是我需要有关动态更改小部件样式的帮助
例如,我想根据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]))));
}
}
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' or
FutureBuilder`结合使用以更新主题数据。您还可以为Flutter提供的类未涵盖的属性构建自定义
Theme
和ThemeData
类。