1
0
mirror of https://github.com/flutter/samples.git synced 2025-11-08 13:58:47 +00:00

Flutter 3.29 beta (#2571)

This commit is contained in:
Eric Windmill
2025-02-12 18:08:01 -05:00
committed by GitHub
parent d62c784789
commit 719fd72c38
685 changed files with 76244 additions and 53721 deletions

View File

@@ -22,9 +22,7 @@ class PlatformChannelSample extends StatelessWidget {
return MaterialApp.router(
title: 'Platform Channel Sample',
theme: ThemeData(
snackBarTheme: SnackBarThemeData(
backgroundColor: Colors.blue[500],
),
snackBarTheme: SnackBarThemeData(backgroundColor: Colors.blue[500]),
),
routerConfig: router(),
);
@@ -75,22 +73,10 @@ class DemoInfo {
}
List<DemoInfo> demoList = [
DemoInfo(
'MethodChannel Demo',
'/methodChannelDemo',
),
DemoInfo(
'EventChannel Demo',
'/eventChannelDemo',
),
DemoInfo(
'Platform Image Demo',
'/platformImageDemo',
),
DemoInfo(
'BasicMessageChannel Demo',
'/petListScreen',
)
DemoInfo('MethodChannel Demo', '/methodChannelDemo'),
DemoInfo('EventChannel Demo', '/eventChannelDemo'),
DemoInfo('Platform Image Demo', '/platformImageDemo'),
DemoInfo('BasicMessageChannel Demo', '/petListScreen'),
];
class HomePage extends StatelessWidget {
@@ -99,9 +85,7 @@ class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Platform Channel Sample'),
),
appBar: AppBar(title: const Text('Platform Channel Sample')),
body: ListView(
children: demoList.map((demoInfo) => DemoTile(demoInfo)).toList(),
),

View File

@@ -14,12 +14,12 @@ class Accelerometer {
/// to value changes from the Accelerometer sensor.
static Stream<AccelerometerReadings> get readings {
return _eventChannel.receiveBroadcastStream().map(
(dynamic event) => AccelerometerReadings(
event[0] as double,
event[1] as double,
event[2] as double,
),
);
(dynamic event) => AccelerometerReadings(
event[0] as double,
event[1] as double,
event[2] as double,
),
);
}
}

View File

@@ -31,24 +31,19 @@ class _AddPetDetailsState extends State<AddPetDetails> {
icon: const Icon(Icons.add),
onPressed: () {
PetListMessageChannel.addPetDetails(
PetDetails(
petType: petType,
breed: breedTextController.text,
),
PetDetails(petType: petType, breed: breedTextController.text),
);
context.pop();
},
)
),
],
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
const SizedBox(
height: 8,
),
const SizedBox(height: 8),
TextField(
controller: breedTextController,
decoration: const InputDecoration(
@@ -58,9 +53,7 @@ class _AddPetDetailsState extends State<AddPetDetails> {
labelText: 'Breed',
),
),
const SizedBox(
height: 8,
),
const SizedBox(height: 8),
RadioListTile<String>(
title: const Text('Dog'),
value: 'Dog',

View File

@@ -15,15 +15,17 @@ class Counter {
/// This method is responsible to increment and return the value of count.
static Future<int> increment({required int counterValue}) async {
final result = await methodChannel
.invokeMethod<int>('increment', {'count': counterValue});
final result = await methodChannel.invokeMethod<int>('increment', {
'count': counterValue,
});
return result!;
}
/// This method is responsible to decrement and return the value of count.
static Future<int> decrement({required int counterValue}) async {
final result = await methodChannel
.invokeMethod<int>('decrement', {'count': counterValue});
final result = await methodChannel.invokeMethod<int>('decrement', {
'count': counterValue,
});
return result!;
}
}

View File

@@ -20,27 +20,32 @@ class EventChannelDemo extends StatelessWidget {
Widget build(BuildContext context) {
final textStyle = Theme.of(context).textTheme.headlineSmall;
return Scaffold(
appBar: AppBar(
title: const Text('EventChannel Demo'),
),
appBar: AppBar(title: const Text('EventChannel Demo')),
body: Center(
child: StreamBuilder<AccelerometerReadings>(
stream: Accelerometer.readings,
builder: (context, snapshot) {
return switch (snapshot) {
AsyncSnapshot(hasError: true) =>
Text((snapshot.error as PlatformException).message!),
AsyncSnapshot(hasError: true) => Text(
(snapshot.error as PlatformException).message!,
),
AsyncSnapshot(hasData: true) => Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('x axis: ${snapshot.data!.x.toStringAsFixed(3)}',
style: textStyle),
Text('y axis: ${snapshot.data!.y.toStringAsFixed(3)}',
style: textStyle),
Text('z axis: ${snapshot.data!.z.toStringAsFixed(3)}',
style: textStyle)
],
),
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'x axis: ${snapshot.data!.x.toStringAsFixed(3)}',
style: textStyle,
),
Text(
'y axis: ${snapshot.data!.y.toStringAsFixed(3)}',
style: textStyle,
),
Text(
'z axis: ${snapshot.data!.z.toStringAsFixed(3)}',
style: textStyle,
),
],
),
_ => Text('No Data Available', style: textStyle),
};
},

View File

@@ -8,8 +8,10 @@ import 'package:flutter/services.dart';
/// from a native asset. The [BasicMessageChannel] uses [StandardMessageCodec]
/// since it supports [Uint8List], which is used to transport the image data.
class PlatformImageFetcher {
static const _basicMessageChannel =
BasicMessageChannel<dynamic>('platformImageDemo', StandardMessageCodec());
static const _basicMessageChannel = BasicMessageChannel<dynamic>(
'platformImageDemo',
StandardMessageCodec(),
);
/// Method responsible for providing the platform image.
static Future<Uint8List> getImage() async {

View File

@@ -22,9 +22,7 @@ class _MethodChannelDemoState extends State<MethodChannelDemo> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('MethodChannel Demo'),
),
appBar: AppBar(title: const Text('MethodChannel Demo')),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
@@ -32,9 +30,7 @@ class _MethodChannelDemoState extends State<MethodChannelDemo> {
'Value of count is $count',
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(
height: 16,
),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
@@ -74,19 +70,17 @@ class _MethodChannelDemoState extends State<MethodChannelDemo> {
},
icon: const Icon(Icons.remove),
label: const Text('Decrement'),
)
),
],
)
),
],
),
);
}
void showErrorMessage(BuildContext context, String errorMessage) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(errorMessage),
),
);
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(errorMessage)));
}
}

View File

@@ -9,11 +9,15 @@ import 'package:flutter/services.dart';
/// This class includes two methods [addPetDetails] and [removePet] which are used
/// to add a new pet and remove a pet from the the list respectively.
class PetListMessageChannel {
static const _jsonMessageCodecChannel =
BasicMessageChannel<dynamic>('jsonMessageCodecDemo', JSONMessageCodec());
static const _jsonMessageCodecChannel = BasicMessageChannel<dynamic>(
'jsonMessageCodecDemo',
JSONMessageCodec(),
);
static const _binaryCodecChannel =
BasicMessageChannel('binaryCodecDemo', BinaryCodec());
static const _binaryCodecChannel = BasicMessageChannel(
'binaryCodecDemo',
BinaryCodec(),
);
/// Method to add a new pet to the list.
///
@@ -43,9 +47,7 @@ class PetListMessageChannel {
/// A model class that provides [petList] which is received from platform.
class PetListModel {
PetListModel({
required this.petList,
});
PetListModel({required this.petList});
final List<PetDetails> petList;
@@ -53,32 +55,30 @@ class PetListModel {
factory PetListModel.fromJson(String jsonString) {
final jsonData = json.decode(jsonString) as Map<String, dynamic>;
return PetListModel(
petList: List.from((jsonData['petList'] as List).map<PetDetails>(
(dynamic petDetailsMap) => PetDetails.fromMap(
petDetailsMap as Map<String, dynamic>,
petList: List.from(
(jsonData['petList'] as List).map<PetDetails>(
(dynamic petDetailsMap) =>
PetDetails.fromMap(petDetailsMap as Map<String, dynamic>),
),
)),
),
);
}
}
/// A simple model that provides pet details like [petType] and [breed] of pet.
class PetDetails {
PetDetails({
required this.petType,
required this.breed,
});
PetDetails({required this.petType, required this.breed});
final String petType;
final String breed;
factory PetDetails.fromMap(Map<String, dynamic> map) => PetDetails(
petType: map['petType'] as String,
breed: map['breed'] as String,
);
petType: map['petType'] as String,
breed: map['breed'] as String,
);
Map<String, String> toJson() => <String, String>{
'petType': petType,
'breed': breed,
};
'petType': petType,
'breed': breed,
};
}

View File

@@ -26,8 +26,10 @@ class _PetListScreenState extends State<PetListScreen> {
// Receives a string of json object from the platform and converts it
// to PetModel.
final scaffoldMessenger = ScaffoldMessenger.of(context);
const BasicMessageChannel<String?>('stringCodecDemo', StringCodec())
.setMessageHandler((message) async {
const BasicMessageChannel<String?>(
'stringCodecDemo',
StringCodec(),
).setMessageHandler((message) async {
if (message == null) {
scaffoldMessenger.showSnackBar(
const SnackBar(
@@ -47,18 +49,17 @@ class _PetListScreenState extends State<PetListScreen> {
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
appBar: AppBar(
title: const Text('Pet List'),
),
appBar: AppBar(title: const Text('Pet List')),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () {
context.go('/petListScreen/addPetDetails');
},
),
body: petListModel.petList.isEmpty
? const Center(child: Text('Enter Pet Details'))
: BuildPetList(petListModel.petList),
body:
petListModel.petList.isEmpty
? const Center(child: Text('Enter Pet Details'))
: BuildPetList(petListModel.petList),
);
}
}
@@ -77,9 +78,7 @@ class BuildPetList extends StatelessWidget {
itemBuilder: (context, index) {
return ListTile(
title: Text('Pet breed: ${petList[index].breed}'),
subtitle: Text(
'Pet type: ${petList[index].petType}',
),
subtitle: Text('Pet type: ${petList[index].petType}'),
trailing: IconButton(
icon: const Icon(Icons.delete),
onPressed: () async {
@@ -90,9 +89,11 @@ class BuildPetList extends StatelessWidget {
const SnackBar(content: Text('Removed successfully!')),
);
} catch (error) {
scaffoldMessenger.showSnackBar(SnackBar(
content: Text((error as PlatformException).message!),
));
scaffoldMessenger.showSnackBar(
SnackBar(
content: Text((error as PlatformException).message!),
),
);
}
},
),

View File

@@ -23,9 +23,7 @@ class _PlatformImageDemoState extends State<PlatformImageDemo> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Platform Image Demo'),
),
appBar: AppBar(title: const Text('Platform Image Demo')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
@@ -47,29 +45,25 @@ class _PlatformImageDemoState extends State<PlatformImageDemo> {
);
} else if (snapshot.connectionState ==
ConnectionState.done) {
return Image.memory(
snapshot.data!,
fit: BoxFit.fill,
);
return Image.memory(snapshot.data!, fit: BoxFit.fill);
}
return const CircularProgressIndicator();
},
),
),
),
const SizedBox(
height: 16,
),
const SizedBox(height: 16),
FilledButton(
onPressed: imageData != null
? null
: () {
setState(() {
imageData = PlatformImageFetcher.getImage();
});
},
onPressed:
imageData != null
? null
: () {
setState(() {
imageData = PlatformImageFetcher.getImage();
});
},
child: const Text('Get Image'),
)
),
],
),
),

View File

@@ -4,7 +4,7 @@ description: A new Flutter project.
version: 1.0.0+1
environment:
sdk: ^3.5.0
sdk: ^3.7.0-0
dependencies:
flutter:

View File

@@ -9,9 +9,7 @@ import 'package:platform_channels/main.dart';
void main() {
group('HomePage tests', () {
testWidgets('HomePage has multiple Text widgets', (tester) async {
await tester.pumpWidget(const MaterialApp(
home: HomePage(),
));
await tester.pumpWidget(const MaterialApp(home: HomePage()));
expect(find.byType(Text), findsWidgets);
});

View File

@@ -14,17 +14,15 @@ void main() {
testWidgets('Enter pet details', (tester) async {
tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler(
const BasicMessageChannel<dynamic>(
'jsonMessageCodecDemo', JSONMessageCodec()),
'jsonMessageCodecDemo',
JSONMessageCodec(),
),
(dynamic message) async {
petList.add(message as Map);
},
);
var router = app.router('/petListScreen/addPetDetails');
await tester.pumpWidget(
MaterialApp.router(
routerConfig: router,
),
);
await tester.pumpWidget(MaterialApp.router(routerConfig: router));
// Enter the breed of cat.
await tester.enterText(find.byType(TextField), 'Persian');

View File

@@ -21,11 +21,7 @@ void main() {
// after decoding the message with codec used by the EventChannel.
void emitValues(ByteData? event) {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.handlePlatformMessage(
'eventChannelDemo',
event,
(reply) {},
);
.handlePlatformMessage('eventChannelDemo', event, (reply) {});
}
// Register a mock for EventChannel. EventChannel under the hood uses
@@ -33,27 +29,26 @@ void main() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMessageHandler('eventChannelDemo', (message) async {
// Decode the message into MethodCallHandler.
final methodCall = standardMethod.decodeMethodCall(message);
// Decode the message into MethodCallHandler.
final methodCall = standardMethod.decodeMethodCall(message);
if (methodCall.method == 'listen') {
// Emit new sensor values.
emitValues(standardMethod.encodeSuccessEnvelope(sensorValues));
emitValues(null);
return standardMethod.encodeSuccessEnvelope(null);
} else if (methodCall.method == 'cancel') {
return standardMethod.encodeSuccessEnvelope(null);
} else {
fail('Expected listen or cancel');
}
});
if (methodCall.method == 'listen') {
// Emit new sensor values.
emitValues(standardMethod.encodeSuccessEnvelope(sensorValues));
emitValues(null);
return standardMethod.encodeSuccessEnvelope(null);
} else if (methodCall.method == 'cancel') {
return standardMethod.encodeSuccessEnvelope(null);
} else {
fail('Expected listen or cancel');
}
});
});
testWidgets('EventChannel AccelerometerReadings Stream test',
(tester) async {
await tester.pumpWidget(const MaterialApp(
home: EventChannelDemo(),
));
testWidgets('EventChannel AccelerometerReadings Stream test', (
tester,
) async {
await tester.pumpWidget(const MaterialApp(home: EventChannelDemo()));
await tester.pumpAndSettle();

View File

@@ -23,9 +23,7 @@ void main() {
return MissingPluginException();
},
);
await tester.pumpWidget(const MaterialApp(
home: MethodChannelDemo(),
));
await tester.pumpWidget(const MaterialApp(home: MethodChannelDemo()));
// Initially the value of count should be 0.
expect(find.text('Value of count is 0'), findsOneWidget);

View File

@@ -12,14 +12,13 @@ import 'package:platform_channels/src/pet_list_screen.dart';
void main() {
group('PetListScreen tests', () {
const basicMessageChannel =
BasicMessageChannel<String?>('stringCodecDemo', StringCodec());
const basicMessageChannel = BasicMessageChannel<String?>(
'stringCodecDemo',
StringCodec(),
);
var petList = [
{
'petType': 'Dog',
'breed': 'Pug',
}
{'petType': 'Dog', 'breed': 'Pug'},
];
PetListModel? petListModel;
@@ -28,29 +27,37 @@ void main() {
// Mock for the pet list received from the platform.
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockDecodedMessageHandler(basicMessageChannel, (message) async {
petListModel = PetListModel.fromJson(message!);
return null;
});
petListModel = PetListModel.fromJson(message!);
return null;
});
// Mock for the index received from the Dart to delete the pet details,
// and send the updated pet list back to Dart.
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockDecodedMessageHandler(
const BasicMessageChannel<ByteData?>(
'binaryCodecDemo', BinaryCodec()), (message) async {
// Convert the ByteData to String.
final index = utf8.decoder.convert(message!.buffer
.asUint8List(message.offsetInBytes, message.lengthInBytes));
const BasicMessageChannel<ByteData?>(
'binaryCodecDemo',
BinaryCodec(),
),
(message) async {
// Convert the ByteData to String.
final index = utf8.decoder.convert(
message!.buffer.asUint8List(
message.offsetInBytes,
message.lengthInBytes,
),
);
// Remove the pet details at the given index.
petList.removeAt(int.parse(index));
// Remove the pet details at the given index.
petList.removeAt(int.parse(index));
// Send the updated petList back.
final map = {'petList': petList};
await basicMessageChannel.send(json.encode(map));
// Send the updated petList back.
final map = {'petList': petList};
await basicMessageChannel.send(json.encode(map));
return null;
});
return null;
},
);
});
test('convert json message to PetListModel', () {
@@ -70,11 +77,9 @@ void main() {
});
testWidgets('BuildPetList test', (tester) async {
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: BuildPetList(petListModel!.petList),
),
));
await tester.pumpWidget(
MaterialApp(home: Scaffold(body: BuildPetList(petListModel!.petList))),
);
expect(find.text('Pet type: Dog'), findsOneWidget);
expect(find.text('Pet breed: Pug'), findsOneWidget);

View File

@@ -12,15 +12,15 @@ void main() {
testWidgets('Platform Image test', (tester) async {
tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler(
const BasicMessageChannel<dynamic>(
'platformImageDemo', StandardMessageCodec()),
'platformImageDemo',
StandardMessageCodec(),
),
(dynamic message) async {
var byteData = await rootBundle.load('assets/eat_new_orleans.jpg');
return byteData.buffer.asUint8List();
},
);
await tester.pumpWidget(const MaterialApp(
home: PlatformImageDemo(),
));
await tester.pumpWidget(const MaterialApp(home: PlatformImageDemo()));
// Initially a PlaceHolder is displayed when imageData is null.
expect(find.byType(Placeholder), findsOneWidget);