Flutter鸿蒙实战
2024-11-06 07:32:17
128次阅读
0个评论
这一节,我们从头开始,做一个完整的应用,
来看一下,使用Flutter写一个具体的鸿蒙应用,
这里面涉及到的知识点有使用网络请求。
创建项目
flutter create --platforms ohos daysmatter
然后运行
flutter run
会发现下面的报错,这时候,我们需要签名。
签完名以后,我们使用下面的代码,进行当前ip地址的请求
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var _ipAddress = 'Unknown';
_getIPAddress() async {
var url = 'https://httpbin.org/ip';
var httpClient = new HttpClient();
String result;
try {
var request = await httpClient.getUrl(Uri.parse(url));
var response = await request.close();
if (response.statusCode == HttpStatus.ok) {
var json = await response.transform(utf8.decoder).join();
var data = jsonDecode(json);
result = data['origin'];
} else {
result =
'Error getting IP address:\nHttp status ${response.statusCode}';
}
} catch (exception) {
result = 'Failed getting IP address';
}
// If the widget was removed from the tree while the message was in flight,
// we want to discard the reply rather than calling setState to update our
// non-existent appearance.
if (!mounted) return;
setState(() {
_ipAddress = result;
});
}
@override
Widget build(BuildContext context) {
var spacer = new SizedBox(height: 32.0);
return new Scaffold(
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('Your current IP address is:'),
new Text('$_ipAddress.'),
spacer,
new ElevatedButton(
onPressed: _getIPAddress,
child: new Text('Get IP address'),
),
],
),
),
);
}
}
接下来,我们继续迁移。
完成整个项目的迁移。
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class ListItem {
final String text1;
final String text2;
final String imageUrl;
ListItem({required this.text1, required this.text2, required this.imageUrl});
}
class MyListPage extends StatefulWidget {
@override
_MyListPageState createState() => _MyListPageState();
}
class _MyListPageState extends State<MyListPage> {
List<ListItem> listItems = [];
@override
void initState() {
super.initState();
fetchData();
}
Future<void> fetchData() async {
// 这里模拟网络请求获取数据
// 实际开发中,您需要替换为您的网络请求代码
final response = await http.get(Uri.parse('https://your_api_endpoint'));
if (response.statusCode == 200) {
final data = json.decode(response.body);
for (var item in data) {
listItems.add(ListItem(
title: item['title'],
desc: item['desc'],
month: item['month'],
));
}
setState(() {});
}
}
void navigateToDetailPage(ListItem item) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailPage(item: item),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('列表页面')),
body: ListView.builder(
itemCount: listItems.length,
itemBuilder: (context, index) {
final item = listItems[index];
return ListTile(
leading: Image.network(item.imageUrl),
title: Text(item.text1),
subtitle: Text(item.text2),
onTap: () => navigateToDetailPage(item),
);
},
),
);
}
}
class DetailPage extends StatelessWidget {
final ListItem item;
DetailPage({required this.item});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('详情页面')),
body: Column(
children: [
Image.network(item.imageUrl),
Text(item.text1),
Text(item.text2),
],
),
);
}
}
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
class NetworkList extends StatefulWidget {
@override
_NetworkListState createState() => _NetworkListState();
}
class _NetworkListState extends State<NetworkList> {
List<dynamic> listData = [];
@override
void initState() {
super.initState();
fetchData();
}
Future<void> fetchData() async {
String token = '123';
HttpClient httpClient = HttpClient();
HttpClientRequest request = await httpClient.postUrl(Uri.parse('your_api_url'));
request.headers.add('Content-Type', 'application/json');
request.write(jsonEncode({'token': token}));
HttpClientResponse response = await request.close();
if (response.statusCode == HttpStatus.ok) {
String responseBody = await response.transform(utf8.decoder).join();
setState(() {
listData = jsonDecode(responseBody);
});
}
httpClient.close();
}
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: listData.length,
itemBuilder: (context, index) {
return ListTile(
leading: Image.network(listData[index]['image_url']),
title: Text(listData[index]['text1']),
subtitle: Text(listData[index]['text2']),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailPage(data: listData[index]),
),
);
},
);
},
);
}
}
class DetailPage extends StatelessWidget {
final dynamic data;
DetailPage({required this.data});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('详情页')),
body: Column(
children: [
Image.network(data['image_url']),
Text(data['text1']),
Text(data['text2']),
],
),
);
}
}
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('点击事件示例'),
),
body: Center(
child: GestureDetector(
onTap: () {
// 在这里添加点击后的操作
print('文本被点击了');
},
child: Text('点击我'),
),
),
),
);
}
}
参考
https://www.geeksforgeeks.org/raised-button-widget-in-flutter/
https://docs.google.com/document/d/1yohSuYrvyya5V1hB6j9pJskavCdVq9sVeTqSoEPsWH0/edit?pli=1
00
- 7回答
- 13粉丝
- 6关注
相关话题
- 鸿蒙Flutter实战:09-现有Flutter项目支持鸿蒙
- 鸿蒙Flutter实战:03-鸿蒙Flutter开发中集成Webview
- 鸿蒙Flutter实战:06-使用ArkTs开发Flutter鸿蒙插件
- 鸿蒙Flutter实战:11-使用 Flutter SDK 3.22.0
- 鸿蒙Flutter实战:07-混合开发
- 鸿蒙Flutter实战:01-搭建开发环境
- 鸿蒙Flutter实战:08-如何调试代码
- 鸿蒙Flutter实战:13-鸿蒙应用打包上架流程
- 鸿蒙Flutter实战:10-常见问题集合
- 鸿蒙Flutter实战:04-如何使用DevTools调试Webview
- Flutter鸿蒙入门
- 鸿蒙Flutter实战:02-Windows环境搭建踩坑指南
- 鸿蒙Flutter实战:12-使用模拟器开发调试
- 鸿蒙Flutter实战:05-使用第三方插件
- Flutter鸿蒙项目创建