How to use same Future another .dart file? (Flutter) - flutter

I'd like to use Future teamMember() in another .dart file. Any contributions are welcome!
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';
void main() {
runApp(new MaterialApp(
home: new Popups(),
));
}
class Popups extends StatefulWidget {
#override
_PopupsState createState() => _PopupsState();
}
class _PopupsState extends State<Popups> {
Future teamMember() async {
await showDialog(
context: context,
...
...

In the other class where you need it create a reference to your popup class and then call teamMember.
class OtherClass extends StatelessWidget {
Popups _popups = Popups();
.
.
RaisedButton(
child: Text("show team member popup"),
onPressed: (){
_popups.teamMember();
}
)
}
hope this helps

Related

How to Initialize Multiple Objects in Flutter VxStore (VelocityX)

Please Check the MUTATION section where I've commented what is the issue:
store.dart
import 'package:velocity_x/velocity_x.dart';
import '../model.dart';
class MyStore extends VxStore {
MyItem? itemA;
MyItem? itemB;
MyStore() {
itemA = MyItem(); // note: 'new' keyword is obsolated now.
itemB = MyItem();
}
}
///----------- MUTATION-------------------///
class PrintMutation extends VxMutation<MyStore> {
#override
void perform() {
print("...............Mutation Starts..................");
store!.itemA!.name = "phone"; // assume we wrote some data into itemA
store!.itemB = store!.itemA; // copying the data to itemB
print('Item B:${store!.itemB!.name!}'); // prints "phone" (as needed)
store!.itemB!.name = 'fruit'; // modifing the name
print('Item A:${store!.itemA!.name!}'); // Item A changes to Fruit, WHY??
}
}
main.dart
import 'package:flutter/material.dart';
import 'package:velocity_x/velocity_x.dart';
import 'core/store.dart';
void main() {
runApp(VxState(child: MyApp(), store: MyStore()));
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () => PrintMutation(),
child: "Print".text.make(),
),
),
);
}
}
pubspec.yaml
dependencies:
velocity_x: ^3.3.0

How do I mock a bloc in Flutter, with states being emitted in response to events from a widget under test

I'm trying to test a widget that makes use of a bloc. I'd like to be able to emit states from my mocked bloc in response to events being fired by the widget under test. I've tried a number of approaches without success. I'm not sure if I'm making some simple error or if I'm approaching the problem all wrong.
Here is a simplified project which demonstrates my issue. (the complete code for this can be found at https://github.com/andrewdixon1000/flutter_bloc_mocking_issue.git)
very simple bloc
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';
class MyBloc extends Bloc<MyEvent, MyState> {
MyBloc() : super(FirstState());
#override
Stream<MyState> mapEventToState(
MyEvent event,
) async* {
if (event is TriggerStateChange) {
yield SecondState();
}
}
}
#immutable
abstract class MyEvent {}
class TriggerStateChange extends MyEvent {}
#immutable
abstract class MyState {}
class FirstState extends MyState {}
class SecondState extends MyState {}
My widget under test
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'bloc/my_bloc.dart';
import 'injection_container.dart';
class FirstPage extends StatefulWidget {
const FirstPage({Key? key}) : super(key: key);
#override
_FirsPageState createState() => _FirsPageState();
}
class _FirsPageState extends State<FirstPage> {
#override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => serviceLocator<MyBloc>(),
child: Scaffold(
appBar: AppBar(title: Text("Page 1")),
body: Container(
child: BlocConsumer<MyBloc, MyState>(
listener: (context, state) {
if (state is SecondState) {
Navigator.pushNamed(context, "SECONDPAGE");
}
},
builder: (context, state) {
if (state is FirstState) {
return Column(
children: [
Text("State is FirstState"),
ElevatedButton(
onPressed: () {
BlocProvider.of<MyBloc>(context).add(TriggerStateChange());
},
child: Text("Change state")),
],
);
} else {
return Text("some other state");
}
},
),
),
),
);
}
}
my widget test
This is where I'm struggling. What I'm doing is loading the widget and then tapping the button. This causes the widget to add an event to the bloc. What I want to be able to do is have my mock bloc emit a state in response to this, such that the widget's BlocConsumer's listener will see the state change the navigate. As you can see from the comment in the code I've tried a few things without luck. Current nothing I've tried results in the listener seeing a state change.
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart' as mocktail;
import 'package:get_it/get_it.dart';
import 'package:test_bloc_issue/bloc/my_bloc.dart';
import 'package:test_bloc_issue/first_page.dart';
class MockMyBloc extends MockBloc<MyEvent, MyState> implements MyBloc {}
class FakeMyState extends Fake implements MyState {}
class FakeMyEvent extends Fake implements MyEvent {}
void main() {
MockMyBloc mockMyBloc;
mocktail.registerFallbackValue<MyState>(FakeMyState());
mocktail.registerFallbackValue<MyEvent>(FakeMyEvent());
mockMyBloc = MockMyBloc();
var nextScreenPlaceHolder = Container();
setUpAll(() async {
final di = GetIt.instance;
di.registerFactory<MyBloc>(() => mockMyBloc);
});
_loadScreen(WidgetTester tester) async {
mocktail.when(() => mockMyBloc.state).thenReturn(FirstState());
await tester.pumpWidget(
MaterialApp(
home: FirstPage(),
routes: <String, WidgetBuilder> {
'SECONDPAGE': (context) => nextScreenPlaceHolder
}
)
);
}
testWidgets('test', (WidgetTester tester) async {
await _loadScreen(tester);
await tester.tap(find.byType(ElevatedButton));
await tester.pump();
// What do I need to do here to mock the state change that would
// happen in the real bloc when a TriggerStateChange event is received,
// such that the listener in my BlocConsumer will see it?
// if tried:
// whenListen(mockMyBloc, Stream<MyState>.fromIterable([SecondState()]));
// and
// mocktail.when(() => mockMyBloc.state).thenReturn(SecondState());
await tester.pumpAndSettle();
expect(find.byWidget(nextScreenPlaceHolder), findsOneWidget);
});
}
I took a look and opened a pull request with my suggestions. I highly recommend thinking of your tests in terms of notifications and reactions. In this case, I recommend having one test to verify that when the button is tapped, the correct event is added to the bloc (the bloc is notified). Then I recommend having a separate test to ensure that when the state changes from FirstState to SecondState that the correct page is rendered (the UI reacts to state changes appropriately). In the future, I highly recommend taking a look at the example apps since most of them are fully tested.

using Flutter google mobile ads and implementing Banner ad is randomly Loading in Log ,

here is my code
[enter image description here][1]
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:provider/provider.dart';
import 'adstate.dart';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
BannerAd bannerAd;
void didChangeDependencies(){
super.didChangeDependencies();
final adState=Provider.of<AdState>(context);
adState.initialization.then((status){
setState(() {
bannerAd= BannerAd(
adUnitId: adState.bannerAdUnitId,
size: AdSize.banner,
request: AdRequest(),
listener:adState.adListener
)..load();
});
});
}
#override
void dispose(){
bannerAd.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("banner ads checking"),
if(bannerAd==null)
SizedBox(height: 50,)
else
Container(
height: 50,
child:AdWidget(
ad: bannerAd,
))
],
),
);
}
}
///
my ad state class
import 'dart:io';
import 'package:google_mobile_ads/google_mobile_ads.dart';
class AdState{
Future<InitializationStatus> initialization;
AdState(this.initialization);
String get bannerAdUnitId => Platform.isAndroid
?'ca-app-pub-3940256099942544/6300978111'
:'ca-app-pub-3940256099942544/6300978111';
AdListener get adListener=> _adListener;
AdListener _adListener=AdListener(
onAdLoaded: (ad) =>print("Ad Loaded:${ad.adUnitId}."),
onAdFailedToLoad: (ad,error) {
print("Ad failed to load:${ad.adUnitId}.$error");
},
onAdOpened: (ad) => print("Ad Loaded:${ad.adUnitId}."),
onAdClosed: (ad) => print("Ad closed:${ad.adUnitId}."),
onAppEvent: (ad,name,data)=>
print("Ad event:${ad.adUnitId}.$name,$data"),
onApplicationExit: (ad) =>print("App Exit:${ad.adUnitId}."),
onNativeAdClicked: (nativeAd)=>
print("Native add clicked:${nativeAd.adUnitId}."),
onNativeAdImpression: (nativeAd)=>
print("Native add Impression:${nativeAd.adUnitId}."),
onRewardedAdUserEarnedReward: (ad,reward)=>
print("Native add Impression:${ad.adUnitId}.${reward.type}"),
);
}
////main Class
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:provider/provider.dart';
import 'package:voiceassistance/homePage.dart';
import 'adstate.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
final initFuture=MobileAds.instance.initialize();
final adsatate=AdState(initFuture);
SystemChrome.setEnabledSystemUIOverlays([]);
runApp(
Provider.value(value: adsatate,
builder: (context, child)=>
MyApp(),
));
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home:BannerAdWidget(),
);
}
}
this my log picturre
[1]: https://i.stack.imgur.com/Yhs39.png
above code loads a banner ad but how can I dispose it , in background it generates de web view logs which compromise the app performance,
please help I am stuck,
above code is saperated by comments (main class, ad mobe class, widget class)
above code loads a banner ad but how can I dispose it , in background it generates de web view logs which compromise the app performance,
please help I am stuck,
above code is saperated by comments (main class, ad mobe class, widget class)
above code loads a banner ad but how can I dispose it , in background it generates de web view logs which compromise the app performance,
please help I am stuck,
above code is saperated by comments (main class, ad mobe class, widget class)
enter image description here

State doesn't change in Flutter app using BLoC

I'm building an app which fetches hotel names from an API. I'm using the BLoC library. I managed to create whole service which downloads the data, but the result doesn't show in my terminal.
My BLoC works, it downloads the data. I saw it in Dart DevTools, but the state doesn't change and it does not show up.
Here's my code:
hotel_bloc.dart
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:hotels/controllers/hotel/hotel_controller.dart';
import 'package:hotels/models/hotel/hotel_model.dart';
import 'package:meta/meta.dart';
part 'hotel_event.dart';
part 'hotel_state.dart';
class HotelBloc extends Bloc<HotelEvent, HotelState> {
HotelBloc() : super(HotelLoading());
final HotelController hotelController = HotelController();
#override
Stream<HotelState> mapEventToState(
HotelEvent event,
) async* {
if (event is FetchEvent) {
yield HotelLoading();
try {
final Hotels hotels = await hotelController.parseHotels();
yield HotelFinal(hotels);
} catch (error) {
HotelError(error);
}
}
}
}
hotel_state.dart
part of 'hotel_bloc.dart';
#immutable
abstract class HotelState {
HotelState();
}
class HotelFinal extends HotelState {
final Hotels hotels;
HotelFinal(this.hotels);
Hotels getHotel() {
return hotels;
}
}
class HotelLoading extends HotelState {
HotelLoading();
}
class HotelError extends HotelState {
final String error;
HotelError(this.error);
}
hotel_event.dart
part of 'hotel_bloc.dart';
#immutable
abstract class HotelEvent {
HotelEvent();
}
class FetchEvent extends HotelEvent {
FetchEvent();
}
hotel_service.dart
import 'package:http/http.dart' as http;
abstract class DownloadService {
Future<http.Response> fetchHotels();
}
class HotelService extends DownloadService {
#override
Future<http.Response> fetchHotels() {
final Uri uri = Uri.https('services.lastminute.com', 'mobile/stubs/hotels');
return http.get(uri);
}
}
hotel_controller.dart
import 'package:hotels/models/hotel/hotel_model.dart';
import 'package:hotels/services/hotel/hotel_service.dart';
class HotelController {
final HotelService hotelService = HotelService();
Future<Hotels> parseHotels() async {
final response = await hotelService.fetchHotels();
final hotels = hotelsFromJson(response.body);
return hotels;
}
}
And finally the HomeScreen
home_screen.dart
import 'package:flutter/material.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hotels/blocs/hotel/hotel_bloc.dart';
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
HotelBloc hotelBloc;
#override
void initState() {
hotelBloc = HotelBloc()..add(FetchEvent());
super.initState();
}
#override
void dispose() {
hotelBloc.close();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('title').tr(),
),
body: BlocConsumer<HotelBloc, HotelState>(
listener: (context, state) {
if (state is HotelError) {
print(state.error);
}
},
builder: (context, state) {
if (state is HotelLoading) {
print('It\'s loading!');
}
if (state is HotelFinal) {
print(state.hotels.toString());
}
return Text('Default text');
},
),
);
}
}
The result is this:
The problem is the you haven't provided the BlocConsumer with your hotelBloc. You want to either have BlocProvider as a parent or use the cubit parameter on BlocConsumer.
BlocConsumer<HotelBloc, HotelState>(
cubit: hotelBloc,
listener:...
builder:...
)

Flutter - auto_route _CustomNavigatorState error

I'm using the auto_route package in order to route my app and until 2 days ago everything worked just fine, until now.
For some reason, I'm getting the following error.
SYSTEM:
flutter: 1.22
dart: 2.10.0
auto_route: ^0.6.7
ERROR:
../../.pub-cache/hosted/pub.dartlang.org/custom_navigator-0.3.0/lib/custom_navigator.dart:60:7: Error: The non-abstract class '_CustomNavigatorState' is missing implementations for these members:
- WidgetsBindingObserver.didPushRouteInformation
Try to either
- provide an implementation,
- inherit an implementation from a superclass or mixin,
- mark the class as abstract, or
- provide a 'noSuchMethod' implementation.
class _CustomNavigatorState extends State<CustomNavigator>
^^^^^^^^^^^^^^^^^^^^^
/opt/flutter/packages/flutter/lib/src/widgets/binding.dart:122:16: Context: 'WidgetsBindingObserver.didPushRouteInformation' is defined here.
Future<bool> didPushRouteInformation(RouteInformation routeInformation) {
main.dart
import 'package:device_simulator/device_simulator.dart';
import 'package:flutter/material.dart';
import 'package:auto_route/auto_route.dart';
import 'Test.gr.dart' as r;
void main() => runApp(MyApp());
const bool debugEnableDeviceSimulator = true;
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
builder: ExtendedNavigator.builder<r.Router>(
router: r.Router(),
builder: (context, extendedNav) => DeviceSimulator(
enable: debugEnableDeviceSimulator,
child:
Scaffold(body: extendedNav, backgroundColor: Colors.red ),
),
),
);
}
}
Also, I should mention, because of some update of flutter I guess, now I need to use r.Router instead of just Router.
Test.dart
import 'package:auto_route/auto_route_annotations.dart';
#MaterialAutoRouter(
routes: <AutoRoute>[],
)
class $Router {}
And also if has any importance here it's the generated file
Test.gr.dart
// GENERATED CODE - DO NOT MODIFY BY HAND
// **************************************************************************
// AutoRouteGenerator
// **************************************************************************
// ignore_for_file: public_member_api_docs
import 'package:auto_route/auto_route.dart';
class Routes {
static const all = <String>{};
}
class Router extends RouterBase {
#override
List<RouteDef> get routes => _routes;
final _routes = <RouteDef>[];
#override
Map<Type, AutoRouteFactory> get pagesMap => _pagesMap;
final _pagesMap = <Type, AutoRouteFactory>{};
}
Do you have any idea what's going one here or how can I fix this? Or if I can't fix this, what can I use instead of the auto_route package which will offer me the same benefice?
i solved this problem with add some function on library CustomNavigator :
Future<bool> didPushRouteInformation(RouteInformation routeInformation) {
return didPushRoute(routeInformation.location);
}
Find the place where the error is generating. Add the following function below there. I did the same and my problem is solved.
Future<bool> didPushRouteInformation(RouteInformation routeInformation) {
return didPushRoute(routeInformation.location);
}