#### Preparations
- Configure the development environment www.jianshu.com/p/ef700c38f…
- Interface open apis at www.wanandroid.com/blog/show/2
- www.iconfont.cn/home/index project image resources
1. New projects
Take a look at the renderings of the first page of the project
- After installing the development environment and opening Android Studio, New Flutter Project will be a little slow for the first time. Install the plug-ins needed for Android Studio development first, as shown below:
2. Add third-party libraries
The project will add dio and flutter_swiper libraries. Using Dio as an example, let’s see how Flutter adds third-party libraries.
-
Go to pub.dev/ and search for dio
-
Click dio to enter and then click Installing to copy the installed version
-
Open the project’s pubspec.yaml file, paste dio: ^3.0.9 in, then click Packages Get
2. Encapsulation of network request tools
import 'package:dio/dio.dart';
class HttpRequest {
static const String baseURL = "https://www.wanandroid.com/";
static const int timeout = 5000;
static final BaseOptions baseOptions =
BaseOptions(baseUrl: baseURL, connectTimeout: timeout);
static final Dio dio = Dio(baseOptions);
static Future<Map<String, dynamic>> request<T>(String url,
{String method = "get", Map<String, dynamic> params, Interceptor inter}) async { final options = Options(method: method); // Interceptor dInter = InterceptorsWrapper(onRequest: (options) {print("\ n = = = = = = = = = = = = = = = = = = request data = = = = = = = = = = = = = = = = = = = = = = = = = =");
print("url = ${options.uri.toString()}");
print("headers = ${options.headers}");
print("params = ${options.data}");
return options;
}, onResponse: (response) {
print("\ n = = = = = = = = = = = = = = = = = = response data = = = = = = = = = = = = = = = = = = = = = = = = = =");
print("code = ${response.statusCode}");
print("data = ${response.data}");
return response;
}, onError: (e) {
print("\ n = = = = = = = = = = = = = = = = = = error response data = = = = = = = = = = = = = = = = = = = = = =");
print("type = ${e.type}");
print("message = ${e.message}");
returne; }); List<Interceptor> inters = [dInter]; Request a separate interceptorif(inter ! = null) { inters.add(inter); } // Uniformly added to interceptors dio.interceptors.addAll(inters); Response<Map<String, dynamic>> response; try { response = await dio.request(url, queryParameters: params, options: options);return response.data;
} on DioError catch (e) {
returnFuture.error(e); }}}Copy the code
3. Data Json parsing process
-
Create an entity to copy the JSON data returned by the network request, and then create an entity using the FlutterJsonBeanFactory plugin, as shown in the following figure
-
Dart requests and parses the data asynchronously
import 'package:flutter_learn/generated/json/banner_entity_helper.dart';
import 'package:flutter_learn/generated/json/home_entity_helper.dart';
import 'package:flutter_learn/model/banner_entity.dart';
import 'package:flutter_learn/model/home_entity.dart';
import 'http_request.dart'; The class HomeRequest {/ / / https://www.wanandroid.com/banner/json / / / get the banner data static Future < BannerEntity > requestBannerList() async { final url ="https://www.wanandroid.com/banner/json";
var response = await HttpRequest.request(url);
BannerEntity entity=BannerEntity();
bannerEntityFromJson(entity, response);
returnentity; } / / / / / http://www.wanandroid.com/article/list/0/json/get home page list data static Future < HomeEntity > requestHomeList (int start) async { final url ="/article/list/$start/json";
var response = await HttpRequest.request(url);
HomeEntity homeEntity=HomeEntity();
homeEntityFromJson(homeEntity, response);
returnhomeEntity; }}Copy the code
4. Create page widgets
- The entry main.dart code
import 'package:flutter/material.dart';
import 'home/home_page.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter widget', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); }}Copy the code
- Home page home_page.dart code
import 'package:flutter/material.dart';
import 'home_content.dart';
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _currentIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(
index: _currentIndex,
children: pages,
),
bottomNavigationBar: BottomNavigationBar(
selectedFontSize: 14,
unselectedFontSize: 14,
currentIndex: _currentIndex,
type: BottomNavigationBarType.fixed,
items: items,
onTap: (index) {
setState(() { _currentIndex = index; }); },),); } // page list list <Widget> pages = [HomePage(), HomePage(), HomePage(), HomePage(), HomePage(),]; //bottomNavigationBar item list List<MyBottomBarItem> items = [ MyBottomBarItem("home"."Home page"),
MyBottomBarItem("wechat"."Public Account"),
MyBottomBarItem("project"."Project"),
MyBottomBarItem("navigate"."Navigation"),
MyBottomBarItem("knowledge"."Body of knowledge")]; class MyBottomBarItem extends BottomNavigationBarItem { MyBottomBarItem(String iconName, String title) : super( title: Text(title), icon: Image.asset("assets/images/tabbar/$iconName.png",
width: 25,
),
activeIcon: Image.asset(
"assets/images/tabbar/${iconName}_active.png",
width: 25,
),
);
}
Copy the code
- Home home_Content.dart code
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Home page"),
),
body: Stack(
children: <Widget>[
HomePageContent(),
],
));
}
}
//banner
class BannerContent extends StatefulWidget {
@override
_BannerContentState createState() => _BannerContentState();
}
class _BannerContentState extends State<BannerContent> {
final List<BannerData> bannerList = [];
@override
void initState() {
super.initState();
HomeRequest.requestBannerList().then((BannerEntity entity) {
setState(() {
if(entity.errorCode == 0) { bannerList.addAll(entity.data); }}); }); } @override Widget build(BuildContext context) {returnBannerWidget(bannerList: bannerList); }} list class HomePageContent extends StatefulWidget {@override _HomePageContentState createState() => _HomePageContentState(); } class _HomePageContentState extends State<HomePageContent> { final List<HomeDataData> homeDataList = []; @override voidinitState() {
super.initState();
HomeRequest.requestHomeList(0).then((HomeEntity entity) {
setState(() {
if(entity.errorCode == 0) { homeDataList.addAll(entity.data.datas); }}); }); } @override Widget build(BuildContext context) {return ListView.builder(
itemCount: homeDataList.length,
itemBuilder: (ctx, index) {
if (index == 0) {
return BannerContent();
} else {
returnHomeListItem(homeDataList[index]); }}); }}Copy the code
- List item home_list_item.dart code
class HomeListItem extends StatelessWidget {
final HomeDataData data;
HomeListItem(this.data);
@override
Widget build(BuildContext context) {
returnContainer( padding: EdgeInsets.all(8), decoration: BoxDecoration( border: Border(bottom: BorderSide(width: 8, color: Color(0xffcccccc)))), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ listRow1(), SizedBox(height: 6), listRow2(), SizedBox(height: 6), listRow3() ], ), ); } // The Widget in the first line of the listlistRow1() {
returnRow( children: <Widget>[ Expanded( flex: 1, child: Text(data.shareUser, style: TextStyle(color: Colors.grey)), ), Text(data.niceShareDate, style: TextStyle(color: Colors.grey)), ], ); } // The Widget in the first line of the listlistRow2() {
returnText(data.title, style: TextStyle(fontSize: 16)); } // The third Widget in the listlistRow3() {
return Row(
children: <Widget>[
Expanded(
flex: 1,
child: Text(data.superChapterName+"/"+data.chapterName, style: TextStyle(color: Colors.grey)), ), Icon(Icons.favorite,color: Color(0xffBFBFBF),size: 18)]); }}Copy the code
- The homepage banner
class BannerWidget extends StatelessWidget {
final List<BannerData> bannerList;
BannerWidget({Key key, this.bannerList}) : super(key: key);
@override
Widget build(BuildContext context) {
returnContainer(width: 750, height: 200, child: Swiper(scrollDirection: Axis. Horizontal, // Horizontal itemBuilder: (BuildContext context, int index) {returnInkWell(onTap: () {// Click on the page}, child: Container(decoration: BoxDecoration(image: DecorationImage(image: NetworkImage("${bannerList[index].imagePath}"), fit: BoxFit.fill, )), )); }, itemCount: bannerList.length, pagination: new SwiperPagination( builder: DotSwiperPaginationBuilder( color: Color.white. WithOpacity (0.5), activeColor: color.white,), margin: edgeinset.all (10),), autoplay:true,
loop: false,),); }}Copy the code
5, summary
I used to think dart nesting was too deep and it was difficult to read. After learning for a while, I found that the control was mostly extracted and it was ok to read. The source code has been uploaded to github.com/xulj-tech/f… And continue to finish later.