# untitled **Repository Path**: lin3308/untitled ## Basic Information - **Project Name**: untitled - **Description**: 实战项目一 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2022-05-14 - **Last Updated**: 2022-07-02 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # untitled 这是一个练习demo 配置vscode启动 1.运行 ->非调试模型运行 -> 选择 flutter/dart **实战项目结构** 1.创建 pages文件夹 2.路由的使用 ``` void main() { runApp(MaterialApp( initialRoute: "/home", // 初始化路由 routes: { "/":(context) => Loading(), "/home":(context) => Home(), "/location":(context) => ChooseLocation() }, )); } ``` ``` // 跳转 FlatButton.icon( onPressed:(){ Navigator.pushNamed(context, "/location"); }, icon:Icon(Icons.edit_location), label: Text("Edit Location"), ) ``` **生命周期** 无状态Widget 1.整个周期所定义的状态不会发生变化 2.所创建的函数只会运行一次 有状态Widget 1.整个周期状态是可以发生变化 2.可以通过setState实现状态更新 initState() 1.widget被创建时执行一次 Build() 1.构建渲染widget 2.一旦使用setState(),就会执行Build() Dispose() 1.一旦widget被删除,就回触发 ``` class _ChooseLocationState extends State { int counter = 0; // 生命周期函数 @override void initState() { super.initState(); print("initState function ran"); } @override Widget build(BuildContext context) { print("build function ran"); return Scaffold( backgroundColor: Colors.grey[200], appBar: AppBar( // AppBar 拥有一个返回功能 backgroundColor:Colors.blue[900], title: Text("选择一个国家"), centerTitle: true, elevation: 0, ), body:RaisedButton( onPressed: (){ setState(() { counter +=1; }); }, child: Text('counter is $counter'), ) ); } @override void dispose() { super.dispose(); print("dispose function ran"); } } ``` **代码异步操作** ``` void getData() async{ //print("flutter"); //代码异步操作 await 先执行后再执行下面的 // 延迟执行 await Future.delayed(Duration(seconds: 3),(){ print("3秒后执行"); }); } ``` **http模块的使用** pub.flutter-io.cn 加载依赖 http: ^0.13.4 使用 import 'package:http/http.dart'; 免费 jsonURL http://jsonplaceholder.typicode.com/ import 'dart:convert'; 解析json ``` void getData() async{ // http request var url = "https://jsonplaceholder.typicode.com/todos/1"; // Response 类型 Response response = await get(Uri.parse(url)); // response.body 才是请求回来的data print(response.body); // json // 解析json 转 map Map data = jsonDecode(response.body); print(data); print(data['title']); } ``` 获取世界时区时间 api worldtimeapi.org ``` void getData() async{ // http request var url = "http://worldtimeapi.org/api/timezone/Asia/Shanghai"; // Response 类型 Response response = await get(Uri.parse(url)); // response.body 才是请求回来的data print(response.body); // json // 解析json 转 map Map data = jsonDecode(response.body); //print(data); //print(data['title']); String datetime = data['datetime']; String offset = data['utc_offset'].substring(1,3); print(datetime); // 创建时间对象 // 格式化时间 并加上时差 DateTime now = DateTime.parse(datetime); now = now.add(Duration(hours: int.parse(offset))); print(now); } ``` **### 封装优化请求方法** 创建一个类 ``` import 'package:http/http.dart'; import 'dart:convert'; class WorldTime{ String? location; String? time; String? flag; // 国旗icon String? url; // 构造方法 WorldTime({this.location,this.flag,this.url}); Future getData() async{ // http request var Url = "http://worldtimeapi.org/api/timezone/$url"; // Response 类型 Response response = await get(Uri.parse(Url)); // response.body 才是请求回来的data // 解析json 转 map Map data = jsonDecode(response.body); //print(data); //print(data['title']); String datetime = data['datetime']; String offset = data['utc_offset'].substring(1,3); // 创建时间对象 // 格式化时间 并加上时差 DateTime now = DateTime.parse(datetime); now = now.add(Duration(hours: int.parse(offset))); print(now); time = now.toString(); } } ``` 调用 ``` String time = 'loading'; void setupWorldTime() async{ WorldTime initState = WorldTime(location: "北京",flag: "China.png",url:'Asia/Shanghai'); // 实例化 类 await initState.getData(); // 等待执行完毕 // 拿到值 print(initState.time); // 状态更新 setState(() { time = initState.time!; }); } ``` 异常捕获和路由传参 try{}catch{} ``` try { // http request var Url = "http://worldtimeapi.org/api/timezone/$url"; // Response 类型 Response response = await get(Uri.parse(Url)); // response.body 才是请求回来的data // 解析json 转 map Map data = jsonDecode(response.body); //print(data); //print(data['title']); String datetime = data['datetime']; String offset = data['utc_offset'].substring(1,3); // 创建时间对象 // 格式化时间 并加上时差 DateTime now = DateTime.parse(datetime); now = now.add(Duration(hours: int.parse(offset))); print(now); time = now.toString(); }catch(e){ print(e); time = "could not get time"; } ``` 从这里开始是 Flutter组件精讲 **flutter 中 MaterialApp 组件的精通使用** MaterialApp 主题 路由 MaterialApp 用来构建MaterialDesign 风格,里面包含了MaterialDesign风格