Flutter Class不工作

时间:2018-06-01 20:10:37

标签: class dart widget flutter

我是Flutter / Dart的新手,所以可能没有使用所有正确的关键词,但我遇到了一个问题,我在课程'FirstPageState'扩展状态下得到一条红线。这使我无法调试应用程序,因此我来到这里希望能够获得解决方案!

这是我的'FirstPage.dart'代码

import 'dart:async';

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

String _FirstPageText = 'Exchange Rates';

class First extends StatefulWidget {
  // This widget is the root of your application.
  @override
  FirstPageState createState() => new FirstPageState();
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text(_FirstPageText),
          centerTitle: true,
          backgroundColor: Colors.black,
        ),
        body: new FeedWidget(),
        ),
      );
  }
}

class FirstPageState extends State<First> {

Future<String> getData() async {
  var response = await http.get(
    'https://jsonplaceholder.typicode.com/posts'
  );

}

}

谢谢你:)

2 个答案:

答案 0 :(得分:5)

如果您阅读&#34;红线&#34;,您会看到错误,可能是State an abstract class期待one or more methods to be defined的错误:

  

实例,getter和setter方法可以是抽象的,定义一个接口,但将其实现留给其他类

在这种情况下,我相信State expects the build method。您可能需要查看documentation behind StatefulWidget,其中描述了必要的内容:

class YellowBird extends StatefulWidget {
  const YellowBird({ Key key }) : super(key: key);

  @override
  _YellowBirdState createState() => new _YellowBirdState();
}

class _YellowBirdState extends State<YellowBird> {
  @override
  Widget build(BuildContext context) {
    return new Container(color: const Color(0xFFFFE306));
  }
}

答案 1 :(得分:0)

您从State&lt; ...&gt;延伸的任何课程必须覆盖build()方法。你已经在错误的地方和错误的方式覆盖了build()方法。

您只需更新代码,如下所示,您的代码就可以使用。

class First extends StatefulWidget {
  @override
  FirstPageState createState() => new FirstPageState();
}
class FirstPageState extends State<First> {

  Future<String> getData() async {
    var response = await http.get(
        'https://jsonplaceholder.typicode.com/posts'
    );
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text(_FirstPageText),
          centerTitle: true,
          backgroundColor: Colors.black,
        ),
        body: new FeedWidget(),
      ),
    );
  }
}