无法从api获取数据

时间:2019-09-04 08:57:07

标签: flutter

虽然我在应用逻辑后从API页面的首页传递值,但我如何不在结果变量中获取数据。我在做什么错了?

这是我传递值的主页-

import 'package:flutter/material.dart';
import 'sourceScreen.dart';
import 'models/API.dart';
class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int value=0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title:Text("uTTerNews")),
      body: Center(
        child: Column(
          children: <Widget>[
            FlatButton(
              onPressed: (){
                Navigator.push(context, MaterialPageRoute(builder: (context)=>SourceScreen({})));
                setState(() {
                  value =1;
                  API(value: value);
                });
              },
              child:Text('India'),
              color: Colors.blue,
            ),
            FlatButton(
              onPressed: (){
                Navigator.push(context, MaterialPageRoute(builder: (context)=>SourceScreen({})));
                setState(() {
                  value =0;
                  API(value: value);
                });
              },
              child:Text('World'),
              color: Colors.blue,
            ),
          ],
        ),
      ),
    );
  }
}

这是我的API页面,我想在其中使用该值以及一些逻辑,下面希望您能理解-

import 'model.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class API{
  int value;
  API({this.value});

  Future<List<Source>> fetchNewsSource() async {
    final world ='https://newsapi.org/v2/sources?apiKey=';
    final india = 'https://newsapi.org/v2/sources?language=en&country=in&apiKey=';
    String result;
    void logic(){
      if(value==1){
        result = india;
      }
      else if(value==0){
        result = world;
      }
    }

    final response = await http.get(result);

    if (response.statusCode == 200) {
      List sources = json.decode(response.body)['sources'];
      return sources.map((source) => new Source.formJson(source)).toList();
    } else {
      throw Exception('Fail to load data');
    }
  }
}

这是主页-

import 'package:flutter/material.dart';
import 'sourceScreen.dart';
import 'models/API.dart';
class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int value=0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title:Text("uTTerNews")),
      body: Center(
        child: Column(
          children: <Widget>[
            FlatButton(
              onPressed: (){
                Navigator.push(context, MaterialPageRoute(builder: (context)=>SourceScreen({})));
                setState(() {
                  value =1;
                  API(value: value);
                });
              },
              child:Text('India'),
              color: Colors.blue,
            ),
            FlatButton(
              onPressed: (){
                Navigator.push(context, MaterialPageRoute(builder: (context)=>SourceScreen({})));
                setState(() {
                  value =0;
                  API(value: value);
                });
              },
              child:Text('World'),
              color: Colors.blue,
            ),
          ],
        ),
      ),
    );
  }
}

来源屏幕

import 'package:flutter/material.dart';
import 'models/model.dart';
import 'models/card.dart';
import 'article.dart';
import 'models/API.dart';

class SourceScreen extends StatefulWidget {
  SourceScreen(Map<int, int> map);

  @override
  _SourceScreenState createState() => _SourceScreenState();
}

class _SourceScreenState extends State<SourceScreen> {
  var list_source;
  var refreshKey = GlobalKey<RefreshIndicatorState>();

  @override
  void initState() {
    super.initState();
    refreshListSource();
  }

  Future<Null> refreshListSource() async {
    API api = new API();
    refreshKey.currentState?.show(atTop: false);
    setState(() {
      list_source = api.fetchNewsSource();
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Color.fromRGBO(58, 66, 86, 1.0),
        appBar: AppBar(
          elevation: 1.0,
          backgroundColor: Color.fromRGBO(58, 66, 86, 1.0),
          title: Text('uTTerNews'),
        ),
        body: Center(
          child: RefreshIndicator(
              child: FutureBuilder<List<Source>>(
                future: list_source,
                builder: (context, snapshot) {
                  if (snapshot.hasError) {
                    Text('Error: ${snapshot.error}');
                  } else if (snapshot.hasData) {
                    List<Source> sources = snapshot.data;
                    return new ListView(
                        children: sources
                            .map((source) =>
                            GestureDetector(
                              onTap: () {
                                Navigator.push(context, MaterialPageRoute(
                                    builder: (context) =>
                                        articleScreen(source: source,)));
                              },
                              child: card(source),
                            ))
                            .toList());
                  }
                  return CircularProgressIndicator();
                },
              ),
              onRefresh: refreshListSource),
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:1)

输出:

enter image description here

尝试完整的代码:

void main() => runApp(MaterialApp(home: Home()));

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int value = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("uTTerNews")),
      body: Center(
        child: Column(
          children: <Widget>[
            FlatButton(
              onPressed: () async {
                value = 1;
                List list = await API(value: value).fetchNewsSource();
                Navigator.push(context, MaterialPageRoute(builder: (context) => SourceScreen(list)));
              },
              child: Text('India'),
              color: Colors.blue,
            ),
            FlatButton(
              onPressed: () async {
                value = 0;
                List list = await API(value: value).fetchNewsSource();
                Navigator.push(context, MaterialPageRoute(builder: (context) => SourceScreen(list)));
              },
              child: Text('World'),
              color: Colors.blue,
            ),
          ],
        ),
      ),
    );
  }
}

class API {
  int value;

  API({@required this.value});

  Future<List<dynamic>> fetchNewsSource() async {
    final world = 'https://newsapi.org/v2/sources?apiKey=$apiKey';
    final india = 'https://newsapi.org/v2/sources?language=en&country=in&apiKey=$apiKey';
    String result;
    if (value == 1)
      result = india;
    else if (value == 0) result = world;

    final response = await http.get(result);

    if (response.statusCode == 200) {
      List sources = json.decode(response.body)['sources'];
      return sources;
    } else {
      throw Exception('Fail to load data');
    }
  }
}

class SourceScreen extends StatefulWidget {
  final List list;

  SourceScreen(this.list);

  @override
  _SourceScreenState createState() => _SourceScreenState();
}

class _SourceScreenState extends State<SourceScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Channels")),
      body: ListView(
        children: widget.list.map((map) => ListTile(title: Text(map["name"]))).toList(),
      ),
    );
  }
}