- 创建 package
flutter create --template=package mypackage
package代码如下:
创建hello_world.dart
///HelloWorld返回hello world 拼接param
class HelloWorld {
String helloWorld(String param) => "hello world ${param}";
}
导出hello_world.dart
library mypackage;
export 'src/hello_world.dart';
- 创建flutter项目
flutter create myflutter
- myflutter pubspec.yaml中引入myPackage
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
mypackage:
path: /Users/administrator/Desktop/workspace/mypackage
- myflutter中调用
import 'package:flutter/material.dart';
import 'package:mypackage/mypackage.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String helloWorld ="";
@override
void initState() {
super.initState();
helloWorld = HelloWorld().helloWorld("我是拼接的字符串!");
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("你好世界"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('${helloWorld}',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 26),)
],
),
),
);
}
}
- 效果展示