你好我是Flutter的新手,我的英文非常糟糕,但我需要有关动态改变小工具风格的帮助
例如,我想根据JSON字段返回的值更改文本颜色。 在这个例子中,文本是amberAccent [400],但取决于我想要更改为其他的JSON字段返回的结果
我可以判刑吗? 怎么样? 谢谢
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]))));
}
}
答案 0 :(得分:2)
您可以使用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' or
FutureBuilder`结合使用,以更新主题数据。
您还可以为Flutter提供的类未涵盖的属性构建自定义Theme
和ThemeData
类。