gpt4 book ai didi

dart - 从 RaisedButton 调用 FutureBuilder

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

我很乐意从 RaisedButton 调用 Future fetchPost 或者换句话说,我不希望 FutureBuilder 在我点击按钮之前做任何事情,我尝试从按钮调用 fetchPost 但它不起作用,我被卡住了。

PS:我使用了此页面中的示例 https://flutter.io/cookbook/networking/fetch-data/

感谢您的帮助。

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

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

Future<Post> fetchPost() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/posts/1');

if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return Post.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}

class Post {
final int userId;
final int id;
final String title;
final String body;

Post({this.userId, this.id, this.title, this.body});

factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}

class FirstFragment extends StatelessWidget {
FirstFragment(this.usertype,this.username);
final String usertype;
final String username;

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

return new SingleChildScrollView(
padding: new EdgeInsets.all(5.0),
child: new Padding(
padding: new EdgeInsets.symmetric(vertical: 0.0, horizontal: 0.0),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Container(
child: new RaisedButton(
child: new Text('Call'),
onPressed: (){
fetchPost();
},
),
),
new Container(
child: FutureBuilder<Post>(
future: fetchPost(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner
return CircularProgressIndicator();
},
)
)
],
),
),
);

}
}

最佳答案

正如 Dhiraj 上面解释的那样,单独调用 fetchPost 不会更改 UI,因此您需要通过调用 setState 来重置 UI。

下面是你的代码应该是什么样子

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

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

Future<Post> fetchPost() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/posts/1');

if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return Post.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}

class Post {
final int userId;
final int id;
final String title;
final String body;

Post({this.userId, this.id, this.title, this.body});

factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}

class FirstFragment extends StatefulWidget {
FirstFragment(this.usertype,this.username);
final String usertype;
final String username;
@override
_FirstFragmentState createState() => new _FirstFragmentState(usertype, username);
}
class _FirstFragmentState extends State<FirstFragment> {
_FirstFragmentState(this.usertype,this.username);
final String usertype;
final String username;
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final Size screenSize = MediaQuery.of(context).size;

return new SingleChildScrollView(
padding: new EdgeInsets.all(5.0),
child: new Padding(
padding: new EdgeInsets.symmetric(vertical: 0.0, horizontal: 0.0),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Container(
child: new RaisedButton(
child: new Text('Call'),
onPressed: (){
fetchPost();
setState(() {
});
},
),
),
new Container(
child: FutureBuilder<Post>(
future: fetchPost(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner
return CircularProgressIndicator();
},
)
)
],
),
),
);

}
}

关于dart - 从 RaisedButton 调用 FutureBuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51100204/

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