how to show the dialog box when session expired or getting response 401 in flutter - json

My application has a user token and it expires after some time the user login. I got response code 401 and want to navigate to the login page, I am using dio and flutter_secure_storage to save tokens.
else if (e.response?.statusCode == 401) {
//here I want to show the dialog box or navigate to the login page
}
print(getDioException(e));
throw Exception(getDioException(e));
}

If you want to show popup please do like below.
else if (e.response?.statusCode == 401) {
showPopUpAlert();//here you have to call your popup function
}
print(getDioException(e));
throw Exception(getDioException(e));
}
//popup UI implementation
showPopUpAlert() {
showDialog(
context: context,
builder: (_) => AlertDialog(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(10.0))),
content: Builder(builder: (context) {
return StatefulBuilder(builder: (context, stateMaintain) {
return SizedBox(
width: Responsive.isMobile(context)
? Responsive.screenWidth(context) / 1.1
: Responsive.screenWidth(context) / 2,
height: 350,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
AutoSizeText('Popup text',
style:
Theme.of(context).textTheme.headline1),
],
),
);
});
}),
));
}

After some time of research, I found the answer.
we need to create a global key for navigating and after we got the 401 we need to navigate the login page.
define global key final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
pass the value in MaterialApp
navigatorKey: navigatorKey,
and use into your class
navigatorKey.currentState?.pushNamed('/LoginScreen');

Related

Get the edited html content in flutter inappwebview using inner HTML

I'm using flutter_inappwebview for to load html content. Html content is loading perfect. It has input field, radio, checkbox etc. It's kind of form. So after loading this HTML content I Can edit and submit the HTML response to the backend side. Here am facing an issue, if I try to edit something and try to get inner html or getHtml content am not getting the newly changed html content. It's always getting the loaded html content.
Tried to check this following post how to detect when inner html changes in flutter webview. But no response.
body: Column(children: <Widget>[
Expanded(
child: InAppWebView(
initialData: InAppWebViewInitialData(
data: '<div id="form-response">' +
widget.htmlTemplate +
'</div>'),
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(javaScriptEnabled: true)),
onLoadStop: (InAppWebViewController controller, url) async {
},
onWebViewCreated: (InAppWebViewController controller) {
_webViewController = controller;
_webViewController.addJavaScriptHandler(
handlerName: 'handleResponse',
callback: (args) {
log('args===$args');
});
},
onConsoleMessage: (controller, consoleMessage) {
print(consoleMessage);
},
gestureRecognizers: <
Factory<OneSequenceGestureRecognizer>>{
Factory<VerticalDragGestureRecognizer>(
() => VerticalDragGestureRecognizer()),
Factory<HorizontalDragGestureRecognizer>(
() => HorizontalDragGestureRecognizer()),
Factory<ScaleGestureRecognizer>(
() => ScaleGestureRecognizer()),
},
),
),
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () async {
// var a=await _webViewController.getHtml();
// print('test1====');
// log(a!);
// var html = await _webViewController.evaluateJavascript(
// source:
// "window.document.getElementsByTagName('html')[0].outerHTML;");
var response=getResponse('S');
log('response$response');
var html = await _webViewController.evaluateJavascript(
source: response);
// "window.document.getElementsByTagName('html')[0].innerHTML;");
// String docu = await _webViewController.evaluateJavascript(source:
// 'document.getElementById("form-response").innerHTML') as String;
//
log('test====');
// log(html);
},
child: Text(
Strings.m081,
style: AppStyle().regularStyle.copyWith(
fontWeight: FontWeight.w600,
fontSize: AppStyle.fontSize14,
color: const Color(0xff1973B9)),
),
)
])
How to get the edited html response?
Is it is happening because the controller am calling in onLoadStop and onWebViewCreated?
Is there a way to receive the text changes stream of a webview textfield/radio/checkbox in flutter?
Is there in any onstate change for controller?

Flutter getx json

First of all, I apologize to everyone for my low level of English. I want to make an application for a live broadcasting radio station. json link of radio site "http://radyo.comu.edu.tr/json/". This link is refreshed every 5 seconds. and json data is also changing. How can I follow a path from the application?
You can cache the response by using flutter cache manager Flutter Cache Manager, store it somewhere and use it. For storage you can use shared preferences,sqlite, hive etc there are a lot of options afterwards
you can use stream builder where data is continually updating
https://api.flutter.dev/flutter/widgets/StreamBuilder-class.html
StreamBuilder<int>(
stream: generateNumbers,
builder: (
BuildContext context,
AsyncSnapshot<int> snapshot,
) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.connectionState == ConnectionState.active
|| snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return const Text('Error');
} else if (snapshot.hasData) {
return Text(
snapshot.data.toString(),
style: const TextStyle(color: Colors.red, fontSize: 40)
);
} else {
return const Text('Empty data');
}
} else {
return Text('State: ${snapshot.connectionState}');
}
},
),

How to mock 'google_maps_flutter' package for flutter tests?

I've recently started getting into flutter, but just as I was about to write a few widget tests, I noticed that I wasn't terribly sure how to mock out the Google Maps Flutter package.
Many examples I've seen include using the library "mockito" to mock out classes, but this assumes that the Google Maps widget will be injected into the widget to be tested. Unfortunately, with their given documentation and startup guide, this doesn't seem to be very possible:
class MapsDemo extends StatefulWidget {
#override
State createState() => MapsDemoState();
}
class MapsDemoState extends State<MapsDemo> {
GoogleMapController mapController;
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(15.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Center(
child: SizedBox(
width: 300.0,
height: 200.0,
child: GoogleMap(
onMapCreated: _onMapCreated,
),
),
),
RaisedButton(
child: const Text('Go to London'),
onPressed: mapController == null ? null : () {
mapController.animateCamera(CameraUpdate.newCameraPosition(
const CameraPosition(
bearing: 270.0,
target: LatLng(51.5160895, -0.1294527),
tilt: 30.0,
zoom: 17.0,
),
));
},
),
],
),
);
}
void _onMapCreated(GoogleMapController controller) {
setState(() { mapController = controller; });
}
}
Note that the GoogleMaps widget cannot be passed in because onMapCreated is a required function, and that function relies private class method (give the parent widget access to GoogleMapsController). Many other examples of mockito mock functions that don't have this sort of callback function to set state.
There doesn't seem to be any other packages I've seen that can effectively mock out the GoogleMaps widget, so I don't really have any sort of example to follow. Ideally, what I was expecting was some sort of behavior like proxyquire or sinon in node.s (where you don't need to pass in the mocked libraries into function.constructors), but it looks like mockified classes need to be passed into the tested widgets.
Are there any other ideas on how to mock out this library for testing? Or should I just live with testing the actual functionality?
I managed to mock the GoogleMaps by mocking the channels it uses:
setUpAll(() async {
SystemChannels.platform_views.setMockMethodCallHandler((MethodCall call) {
switch (call.method) {
case 'create':
return Future<int>.sync(() => 1);
default:
return Future<void>.sync(() {});
}
});
MethodChannel('plugins.flutter.io/google_maps_0', StandardMethodCodec())
.setMockMethodCallHandler((MethodCall methodCall) async {
return null;
});
}
I got inspiration from this webview plugin test (which is a PlatformView like the GoogleMaps widget), as well as this GoogleMaps plugin test

Flutter map_view use map_view as widget

I would like to ask on how to show the map fullscreen using the function MapView.Show function on map_view dart framework which I couldn't implement as a widget in flutter. see my code below:
MapView showMap() {
return _mapView.show(new MapOptions(
mapViewType: MapViewType.normal,
initialCameraPosition:
new CameraPosition(new Location(10.31264, 123.91139), 12.0),
showUserLocation: true,
));
}
should be put inside the child in widget.
#override
Widget build(BuildContext context) {
return new Container(
color: Colors.red,
height: double.infinity,
width: double.infinity,
child: showMap(), // surprisingly not working
);
}
I looked into tutorials on this implementation but it seems I haven't seen any liable sources on this implementation. Does anyone knew how to implement this one? Thanks!
Note: I want to implement as a fullscreen widget.
As far as I know, you have to show the Map_View calling a function when an event happens (like when a button is pressed). It's not a Widget like a Text or a Padding.
If you want to open a fullscreen Map I'd suggest you to try, for example, this.
#override
Widget build(BuildContext context) {
return new Container(
color: Colors.red,
height: double.infinity,
width: double.infinity,
child: Center(
child: RaisedButton(
onPressed: () => showMap(),
child: Text("Click me!"),
),
),
);
}

How to show custom warning when FutureBuilder snapshot data equals to 0 (zero)?

In my Flutter app body section I use FutureBuilder. If snapshot.hasData then I show the Data in body. My problem is that sometimes the snapshot data is 0 (zero). I need to use stack or similar to show user a warning with stating that “currently data is not available”. How do I do that?
body: new Center(
child: new FutureBuilder(
future: getCurrencyJsonData(),
builder: (context, snaphot) {
if (snaphot.hasData) {
return new ListView(
Just add a if into your builder..
if (snaphot.data.length == 0) {
return new Stack(...);
}