从RaisedButton调用FutureBuilder

时间:2018-06-29 10:59:20

标签: dart flutter

我很乐意通过 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();
                },
              )
            )
          ],
        ),
      ),
    );

  }
}

2 个答案:

答案 0 :(得分:1)

仅调用fetchPost不会更改UI。

首先在内部版本中执行futurebuilder,它从fetchPost获取数据。

然后要重新获取agiain,则需要重建。

要在onPressed的升高按钮内部进行操作:

onPressed: (){
               setState((){})
             },

要仅在单击按钮时获取帖子(不是第一次),您应该使用then()

详细信息:https://www.dartlang.org/tutorials/language/futures

答案 1 :(得分:1)

如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();
                },
              )
            )
          ],
        ),
      ),
    );

  }
}