FutureBuilder< ?>Flutter

vc9ivgsu  于 2023-06-07  发布在  Flutter
关注(0)|答案(1)|浏览(205)

我想在FAB被点击时从API获取数据。
我已经阅读了与此相关的文档(https://docs.flutter.dev/cookbook/networking/fetch-data),尽管FutureBuilder的类型有问题。
同样的方法可以定义一个Future,但不能为FutureBuilder做同样的事情。

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

class Event {
  Event({
    required this.name,
    required this.desc,
    required this.eventDate,
    required this.pic,
    required this.price,
    required this.events,
  });

  String name;
  String desc;
  String eventDate;
  String pic;
  int price;
  List<String> events;

  factory Event.fromJson(Map<String, dynamic> json) => Event(
    name: json["name"],
    desc: json["desc"],
    eventDate: json["eventDate"],
    pic: json["pic"],
    price: json["price"],
    events: List<String>.from(json["events"].map((x) => x)),
  );

  Map<String, dynamic> toJson() => {
    "title": name,
    "description": desc,
    "eventDate": eventDate,
    "pic": pic,
    "price": price,
    "images": List<dynamic>.from(events.map((x) => x)),
  };
}

Future<Event> fetchEvents() async {

  final response = await http.get(Uri.parse('localhost:3007/events'));

  if (response.statusCode == 200) {
    // If server returns a 200 > response OK > parse the JSON
    return Event.fromJson(jsonDecode(response.body));
  }

  else {
    throw Exception('Failed to load events');
  }

}

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

  State<EventList> createState() => _EventListState();
}

class _EventListState extends State<EventList> {

  String eventsAPI = 'localhost:3007/events';

  late Future<Event> futureEvent;

  void initState() {
     super.initState();
     futureEvent = fetchEvents();
  }

  Widget build(BuildContext context) => MaterialApp(
    debugShowCheckedModeBanner: false,

    home: Scaffold(
      backgroundColor: Colors.green[500],

      appBar: AppBar(
          centerTitle: true,
          title: const Text('Listado Eventos', style: TextStyle(fontSize: 40)),
          backgroundColor: Colors.green[900],
        ),

      body: Stack(
        children: [
          Padding(
            padding: const EdgeInsets.all(12),
            child: Align(
              alignment: Alignment.bottomRight,
              child: FloatingActionButton(
                heroTag: 'GET',
                backgroundColor: Colors.green[900],
                onPressed: null,
                child: const Text('GET', style: TextStyle(fontSize: 15)),

              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(12),
            child: Align(
              alignment: Alignment.bottomLeft,
              child: FloatingActionButton(
                heroTag: 'BACK',
                backgroundColor: Colors.green[900],
                onPressed: backHome,
                child: const Text('BACK', style: TextStyle(fontSize: 15)),
              ),
            ),
          ),
        ],
      )

    ),

  );

  void backHome() {
    Navigator.pushNamed(context, 'backHome');
  }

  // error
  FutureBuilder<Eve>

}

不知道有没有人能帮上忙,提前谢谢!

0yycz8jy

0yycz8jy1#

首先,你想用这些数据做什么?用数据构建UI逻辑?
下面是你应该如何使用FutureBuilder来构建未来函数的UI。

FutureBuilder(
 future: http.get(Uri.parse('localhost:3007/events')),
 builder: (context, snapshot) {
  if (snapshot.hasData){
   return Widget()
  }
  return CircularProgressIndicator()
 },
)

相关问题