哈希空间

Flutter 写一个网络加载的图文列表页面

  1. 创建一个新的Flutter项目,命名为“network_list”。

  2. 在pubspec.yaml文件中添加http和cached_network_image插件:

dependencies:
  flutter:
    sdk: flutter
  http: ^0.12.2
  cached_network_image: ^2.5.0
  1. 在lib文件夹中创建一个新的文件夹“models”,用于存放数据模型类。在models文件夹中创建一个新的dart文件“post.dart”,定义一个名为“Post”的数据模型类:
class Post {
  int id;
  String title;
  String body;
  String imageUrl;

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

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'],
      title: json['title'],
      body: json['body'],
      imageUrl: json['imageUrl'],
    );
  }
}
  1. 在lib文件夹中创建一个新的文件夹“services”,用于存放网络请求相关的类。在services文件夹中创建一个新的dart文件“api_service.dart”,定义一个名为“ApiService”的网络请求类:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:network_list/models/post.dart';

class ApiService {
  static const String apiUrl = 'https://jsonplaceholder.typicode.com/posts';

  Future<List<Post>> getPosts() async {
    final response = await http.get(apiUrl);

    if (response.statusCode == 200) {
      final List<dynamic> jsonData = json.decode(response.body);
      return jsonData.map((post) => Post.fromJson(post)).toList();
    } else {
      throw Exception('Failed to load posts');
    }
  }
}
  1. 在lib文件夹中创建一个新的文件夹“widgets”,用于存放UI相关的小部件。在widgets文件夹中创建一个新的dart文件“post_card.dart”,定义一个名为“PostCard”的小部件,用于显示单个帖子:
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:network_list/models/post.dart';

class PostCard extends StatelessWidget {
  final Post post;

  PostCard({this.post});

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          CachedNetworkImage(
            imageUrl: post.imageUrl,
            placeholder: (context, url) =>
                Center(child: CircularProgressIndicator()),
            errorWidget: (context, url, error) => Icon(Icons.error),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  post.title,
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                ),
                SizedBox(height: 8),
                Text(post.body),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
  1. 在lib文件夹中创建一个新的dart文件“main.dart”,在其中编写主要的UI代码:
import 'package:flutter/material.dart';
import 'package:network_list/models/post.dart';
import 'package:network_list/services/api_service.dart';
import 'package:network_list/widgets/post_card.dart';

void main() => runApp(NetworkListApp());

class NetworkListApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Network List',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: NetworkListPage(),
    );
  }
}

class NetworkListPage extends StatefulWidget {
  @override
  _NetworkListPageState createState() => _NetworkListPageState();
}

class _NetworkListPageState extends State<NetworkListPage> {
  final ApiService apiService = ApiService();
  Future<List<Post>> futurePosts;

  @override
  void initState() {
    super.initState();
    futurePosts = apiService.getPosts();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Network List'),
      ),
      body: Center(
        child: FutureBuilder(
          future: futurePosts,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (context, index) {
                  return PostCard(post: snapshot.data[index]);
                },
              );
            } else if (snapshot.hasError) {
              return Text("${snapshot.error}");
            }

            return CircularProgressIndicator();
          },
        ),
      ),
    );
  }
}
  1. 运行应用程序,即可在主页上看到加载的帖子列表。

本文 最佳观看地址:https://www.hashspace.cn/flutter-network-list.html 阅读 928

打开 哈希空间 微信小程序中查看更佳