#StackBounty: #flutter #dart Flutter how to subtract time from other time

Bounty: 250

I have 2 times which I need to do subtract and I am almost close but there is one big issue

I have 2 times in string-like 10:00AM and 10:00PM

And my code is this

   var df =  DateFormat("hh:mm");                                           
   var durationStart =  DateFormat('HH:mm').format(df.parse(10:00AM));
   var durationEnd =  DateFormat('HH:mm').format(df.parse(10:00PM));
  
   print('durationStart ${durationStart}');
   print('durationEnd ${durationEnd}');


   var Startparts = durationStart.split(':');
   var startDurationSet = Duration(hours: int.parse(Startparts[0].trim()), minutes: int.parse(Startparts[1].trim()));


   var Endparts = durationEnd.split(':');
   var endDurationSet = Duration(hours: int.parse(Endparts[0].trim()), minutes: int.parse(Endparts[1].trim()));


   print('startDurationSet ${startDurationSet}');

   var result = Duration(hours: int.parse(Endparts[0].trim()) - int.parse(Startparts[0].trim()) , minutes: int.parse(Startparts[1].trim()) - int.parse(Endparts[1].trim()));
    
       print('result ${result.toString().replaceAll('-', '')}');

So I have 2 times one is startTime and one is End time. I simply need a difference between hours. for example, I have 10:00Am and 01:00PM i need 3hours but it’s showing 9hours. But what I am receiving is if I have 10:00AM and 10:00pm it’s showing 0 hours but its needs to show 12. Same


Get this bounty!!!

#StackBounty: #java #android #flutter #android-studio Flutter doctor results with "cmdline-tools component is missing"

Bounty: 50

I have tried the answers at here & here to no avail.

After installing Android Studio & Flutter on Windows 10, when I run flutter doctor, I get the following:

[√] Flutter (Channel stable, 2.5.0, on Microsoft Windows [Version 10.0.19043.1202], locale en-US)
[X] Android toolchain - develop for Android devices
    X cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
[√] Chrome - develop for the web
[√] Android Studio (version 2020.3)
[√] VS Code (version 1.60.0)
[√] Connected device (2 available)

Opening Android Studio > SDK Manager > Android SDK > SDK Tools uninstalling and re-installing Android SDK Command-line Tools (latest) has no effect.

I have also added <pathToSDK>toolsbin, <pathToSDK>platform-tools, and <pathToSDK>cmdline-toolslatestbin to the user PATH environment variables.

Following the flutter instructions and running <pathToSDKManager> --install "cmdline-tools;latest" (Which for me is located in <pathToSDK>cmdline-toolslatestbin) results with:

ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.

I haven’t been able to find any documentation on this other than that I need to install some version on Java and add it to my path. The https://flutter.dev/docs/get-started/install/windows page mentions "Make sure that you have a version of Java 8 installed and that your JAVA_HOME environment variable is set to the JDK’s folder." and then states "Android Studio versions 2.2 and higher come with a JDK, so this should already be done." but doesn’t elaborate further.

Opening Android Studio and going to File > Project Structure > Project > Project SDK I can see that Android Studio already recognized several versions of Java installed:

enter image description here


Get this bounty!!!

#StackBounty: #json #flutter #api #dart #flutter-layout Unable to send the intercepted sms using REST API in flutter dart

Bounty: 50

Problem:
I am trying to intercept the SMS message body and then send the message body to the database using a POST Call REST API every time I encounter an SMS. This whole interception and sending the message body should work in the background as well and that too automatically.

What I have achieved so far:
I am using the telephony plugin to intercept the message body and I am able to print the message body every time I receive one at the UI level but unable to call the API and send the SMS body.

Error:
Since I did not find a way to how to automatically call the API every time a new message is intercepted so I used a button to call it instead but even that did not work and it throws the error as

[error:flutter/lib/ui/ui_dart_state.cc(209)] unhandled exception: invalid argument(s) (onerror): the error handler of future.catcherror must return a value of the future's type

Also, I did not manage how do I intercept the SMS message body in the background.

To better understand this error I will be attaching a few of my code snippets:

API usage function:

String body = "";
  DateTime currentPhoneDate = DateTime.now();
  final telephony = Telephony.instance;
  interceptMessage() {
    final messaging = ApiService();
    messaging.interceptedMessage({
      "id": 50,
      "body": "$body",
      "senderName": "IDK",
      "timeStamp": "2021-10-02 12:00:55"
    })
      ..then((value) {
        if (value.status == "Success") {
          print('Message Intercepted');
        } else {
          print('Somethig went wrong');
        }
      });
  }

API Class:

Future<SmsResponse> interceptedMessage(dynamic param) async {
    var client = http.Client();

    String? token = await storage.readSecureToken('key');
    if (token == null) {
      throw Exception("No token stored in storage");
    }
    try {
      var response = await client
          .post(
            Uri.https("baseURL", "endpoint"),
            headers: <String, String>{
              'Authorization': 'Token $token',
            },
            body: param,
          )
          .timeout(Duration(seconds: TIME_CONST))
          .catchError(handleError);
      if (response.statusCode == 200) {
        print('Response Body: ${response.body}');
        final data = await jsonDecode(response.body);
        return SmsResponse.fromJson(data);
      } else if (response.statusCode == 401) {
        print("Unauthorized Request");
        return param;
      } else {
        print("Bad Input");
        return param;
      }
    } catch(e){
      print(e);
   }
  }

Telephony Plugin Usage:

 @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  onMessage(
    SmsMessage message,
  ) async {
    setState(() {
      body = message.body ?? "Error reading message body.";
      print("$body");
    });
  }

  onSendStatus(SendStatus status) {
    setState(() {
      body = status == SendStatus.SENT ? "sent" : "delivered";
    });
  }

  Future<void> initPlatformState() async {
    final bool? result = await telephony.requestPhoneAndSmsPermissions;

    if (result != null && result) {
      telephony.listenIncomingSms(
        onNewMessage: onMessage,
        onBackgroundMessage: onBackgroundMessage,
        listenInBackground: true,
      );
    }
    if (!mounted) return;
  }

Handle Error Function

void handleError(error) {
    //hideLoading();
    if (error is BadRequestException) {
      var message = error.message;
      DialogHelper.showErroDialog(description: message);
    } else if (error is FetchDataException) {
      var message = error.message;
      DialogHelper.showErroDialog(description: message);
    } else if (error is ApiNotRespondingException) {
      DialogHelper.showErroDialog(
          description: 'Oops! It took longer to respond.');
    } else if (error is SocketException) {
      print(
          error); //Have to remove this part this is already being handled at the service level
    } else {
      print("All OK");
    }
  }

UI Level:

Text("$body");


Get this bounty!!!

#StackBounty: #ios #flutter #flutter-ios #flutter-ios-build Unable to build flutter app with firebase auth in Xcode

Bounty: 50

I’m building a flutter mobile application with firebase_auth to authenticate. It’s run well on android. But when i’m try to build it on ios using xcode it gives me series of erros.

I have added the GoogleService-info.plist file inside Runner folder using xcode and added the Firebase.configure() code potion in AppDeligate.swift file. But still not working for me.

enter image description here


Get this bounty!!!

#StackBounty: #opengl #shaders #textures #flutter Render 3 textures into an RGB texture?

Bounty: 50

Flutter has support for external textures, but they have to be RGB. I want to render YUV video to Flutter.

On OpenGL I used to create 3 textures, and upload Y,U,V to each corresponding texture. Then I’d paint the screen using these 3 textures, forming an RGB image.

On Flutter, I need to render to a RGB texture. Is there a way to still do the YUV conversion using OpenGL, and then render to the flutter’s RGB texture?

Maybe rendering to Y,U,V textures and them rendering to the RGB texture from these 3 textures?


Get this bounty!!!

#StackBounty: #firebase #flutter #google-cloud-firestore #stream-builder StreamBuilder's Firebase query appears and disappears inst…

Bounty: 50

I am trying to query a Stream where the document should have ‘UretimKurulum‘ in ‘unit‘ array and the ‘date‘ should be equal or greater than today’s date.

While streaming this query I do get the correct results that I want for a brief seconds and then it says ‘No Data Available’.

Database

Below is the actual code:

  final FirebaseFirestore _db = FirebaseFirestore.instance;

  final DateTime _now = DateTime.now();
  final String val = 'UretimKurulum';

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot<Object>>(
      stream: _db.collection('Schedule').where('date', isGreaterThanOrEqualTo: _now).where('unit', arrayContains: val).snapshots(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(child: LinearProgressIndicator());
        } else {
          if (!snapshot.hasData) {
            return Center(child: Text('No Data Available'));
          } else {
            return ListView.builder(
              itemCount: snapshot.data!.docs.length,
              itemBuilder: (context, index) {
                var docSnap = snapshot.data!.docs[index];
                return Text(docSnap.id);
              },
            );
          }
        }
      },
    );
  }
}

If I try to remove:

if (!snapshot.hasData) {
            return Center(child: Text('No Data Available'));
          }

I get the following error:

════════ Exception caught by widgets library ═══════════════════════════════════
The following TypeErrorImpl was thrown building StreamBuilder<QuerySnapshot<Object>>(dirty, state: _StreamBuilderBaseState<QuerySnapshot<Object>, AsyncSnapshot<QuerySnapshot<Object>>>#0508a):
Unexpected null value.

Error Message


Get this bounty!!!

#StackBounty: #flutter #dart merge three models and filter them out by id in Dart?

Bounty: 50

I faced such a problem: I have a Home page where I show all kinds of drinks in the menu and I want to create a page where the user clicks and get a filtered list, where drinks are already divided into hot and cold according to their ID. I know that the method where is used to filter by ID. But my problem is that I have not just two models which have the same id’s in them, but plus another two models through which I have to filter the values and get the already filtered values from the FilterMenu model. I don’t know how to solve this problem correctly. Please, help me, if you can.

Also addition: all models are entitled by each other by their id’s, so DessertId is bond with DrinksId by mv_id and DrinksId is bonded with FilterMenu by sId.

I thought about combining all these models together and then filtering, but I don’t know how to do it correctly. Is it necessary to merge all the models here?

My models:

class DessertsId {
  final int mvId;
  final int mrId;

  DessertsId({this.mvId, this.mrId});
}

class DrinksId{
  final int mvId;
  final int sId;
  DrinksId({this.mvId, this.sId});
}

from this models i want to get all filtrated items through the previous 2

class FilterMenu{
  final String mTitle;
  final int sId;
  FilterMenu({this.mTitle, this.sId});
}

My first page where user taps and go to the filterted Page:

class Home extends StatelessWidget {
   Home({Key key}) : super(key: key);

  @override
  List<CommonMenu> common = <CommonMenu>[
    CommonMenu(commonTitle: 'Hot Drinks', mrId: 2),
    CommonMenu(commonTitle: 'Cold Drinks', mrId: 1),
  ];
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: ListView.builder(
        itemCount: common.length,
          itemBuilder: (context, index){
        return ListTile(
          title: Text(common[index].commonTitle),
          onTap: () {
            Navigator.push(context,
                MaterialPageRoute(builder: (context) => Menu(

                )));
          },
        );
      }),
    );
  }
}

My second page where should be all filtered items store:

class Menu extends StatefulWidget {
  final int sId;

  const Menu({Key key, this.sId}) : super(key: key);

  @override
  _MenuState createState() => _MenuState();
}

class _MenuState extends State<Menu> {
  List<DessertsId> desert = <DessertsId>[
    DessertsId(mvId: 1, mrId: 1),
    DessertsId(mvId: 2, mrId: 2),
    DessertsId(mvId: 1, mrId: 1),
    DessertsId(mvId: 2, mrId: 2),
    DessertsId(mvId: 2, mrId: 2),
  ];

  List<DrinksId> drinks = <DrinksId>[
    DrinksId(mvId: 1, sId: 1),
    DrinksId(mvId: 2, sId: 2),
    DrinksId(mvId: 1, sId: 1),
    DrinksId(mvId: 2, sId: 2),
    DrinksId(mvId: 1, sId: 1),
    DrinksId(mvId: 2, sId: 2),
  ];

  List<FilterMenu> filterMenu = <FilterMenu>[
    FilterMenu(mTitle: 'capuchino', sId: 1),
    FilterMenu(mTitle: 'americano', sId: 2),
    FilterMenu(mTitle: 'latte', sId: 1),
    FilterMenu(mTitle: 'tonic', sId: 2),
    FilterMenu(mTitle: 'ice latte', sId: 1),
    FilterMenu(mTitle: 'frapuchino', sId: 2),
  ];

  @override
  Widget build(BuildContext context)  {
    return Scaffold(
        appBar: AppBar(),
        body: ListView.builder(
          itemCount: filterMenu.length,
          itemBuilder: (context, index) {
            return ListTile(
              title: Text(filterMenu[index].mTitle),
            );
          },
        ));
  }
}

This is the code I try to filtrate and combined models:

Iterable<CommonItems> merged(List <DessertsId> desert,
        List <DrinksId> drinks, List <FilterMenu> filterMenu) sync* {
      for (var i = 0; i < filterMenu.length; i++) {
        var desertes = desert.where((element) => element.mrId == filterMenu[i].sId).toList();
        var drink = drinks.where((element) => element.sId == filterMenu[i].sId).toList();
        yield CommonItems(
          desert: desertes,
          drinks: drink,
          mrId: filterMenu[i].sId,
          sId: filterMenu[i].sId
        );
      }
    }
    List<CommonItems> common = merged(desert, drinks, filterMenu).toList();

class CommonItems{
  final int sId;
  final int mrId;
 final List<DessertsId> desert;
  final List<DrinksId> drinks;
  List<FilterMenu> filterMenu;
  final List <CommonMenu> menu;

  CommonItems({this.desert, this.drinks, this.menu, this.sId, this.mrId});
}

The screenshots:

first page

second page with filtered items


Get this bounty!!!

#StackBounty: #flutter #flutter-provider StreamProvider returns no data when used with Navigator

Bounty: 50

The issue is that I don’t get any values out of my StreamProviders (which are defined on a global level) within my Authenticated route:

  runApp(MultiProvider(
    providers: [
      Provider.value(value: userService),
      StreamProvider.value(value: authService.userStream, initialData: null),
      StreamProvider.value(value: userService.userDataStream),
      StreamProvider.value(value: userService.characterStream),
    ],
    child: MyApp(),
  ));
}

I noticed that it’s to do with the logic that I have for my Navigator (if I remove it the provider values are passed down the widget tree as expected). The Navigator I’m using is based around the idea that the app has 3 states: Not Authenticated, Authenticated and Authenticated-First-Time. I get the value whether I’m authenticated from the loginStream (so far everything works):

@override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: loginStream,
      builder: (ctx, snapshot) {
        if (!snapshot.hasData) return Loading();
        LoginState state = snapshot.data;
        if (state == LoginState.LOGGED_OUT) return LoginScreen();
        if (state == LoginState.FIRST_TIME) return CharacterCreationScreen();
        return Navigator(
          key: navigatorKey,
          initialRoute: "/home",
          onGenerateRoute: (settings) => PageRouteBuilder(
            pageBuilder: (ctx, _, __) => routes(settings)(ctx),
            transitionsBuilder: pageTransition,
          ),
        );
      },
    );

The thing is that if I’m Authenticated and say in the HomeScreen, then both userDataStream and characterStream return null even if there’s actual data available. If I remove the StreamBuilder + LoginLogic itself and just have the Navigator widget returned above, then HomeScreen gets the correct values.

UPDATE:
I noticed that it’s not even the StreamBuilder. If I remove the 3 if’s within the builder, then the stream values are propagated correctly. Not sure why that happens.


Get this bounty!!!

#StackBounty: #firebase #flutter #google-cloud-functions #firebase-tools Run Firebase Callable HTTP Cloud Function locally

Bounty: 50

I’ve a deployed a callable function, say foo, using

firebase deploy --only functions:foo

and I’m calling it in Flutter using:

var result = await FirebaseFunctions.instance.httpsCallable('foo')();
var data = result.data;

All good. But I’d like to run this function in the Firebase Emulator. When I run

firebase emulators:start --only functions

I can see the emulator up and running, and I’m connecting my Flutter app to the emulator using:

FirebaseFunctions.instance.useFunctionsEmulator('localhost', 4000);

However, I don’t know how to invoke the callable foo in Flutter using the Firebase Emulator. I saw this related thread but it doesn’t really answer my question.


EDIT:

Here’s the console output:

✔  functions[us-central1-foo]: http function initialized (http://localhost:5001/my_project/us-central1/foo).

┌─────────────────────────────────────────────────────────────┐
│ ✔  All emulators ready! It is now safe to connect your app. │
│ i  View Emulator UI at http://localhost:4000                │
└─────────────────────────────────────────────────────────────┘

┌───────────┬────────────────┬─────────────────────────────────┐
│ Emulator  │ Host:Port      │ View in Emulator UI             │
├───────────┼────────────────┼─────────────────────────────────┤
│ Functions │ localhost:5001 │ http://localhost:4000/functions │
├───────────┼────────────────┼─────────────────────────────────┤
│ Firestore │ localhost:8080 │ http://localhost:4000/firestore │
└───────────┴────────────────┴─────────────────────────────────┘
  Emulator Hub running at localhost:4400
  Other reserved ports: 4500

I tried

useFunctionsEmulator('localhost', 4000);
useFunctionsEmulator('localhost', 5001);

but both of them throw the following error on calling httpsCallable('foo') but without the emulators, this function does work.

[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [firebase_functions/unavailable] UNAVAILABLE


Get this bounty!!!

#StackBounty: #flutter #dictionary #dart Real-Time Updates with Streambuilder in Flutter and Google Maps (Firestore)

Bounty: 50

I have a sample app that I am building that fetches multiple markers from Firestore and displays them on Google Maps.

The issue is that the changes (markers added/deleted/updated) aren’t displayed in real time since it only rebuilds in init state. I think that I could use Stream Builder to listen to the changes and update them in real time.

I am not sure how to do it with Google Maps and Firestore, since the syntax is kinda weird with snapshots, I tried many ways, but not successful. Here’s my code:

  @override
  void initState() {
    populateMarkers();
    super.initState();
   }


populateMarkers() {
    FirebaseFirestore.instance.collection('marker').get().then((documents) {
      if (documents.docs.isNotEmpty) {
        for (int i = 0; i < documents.docs.length; i++) {
          initMarker(
              documents.docs[i].data(), documents.docs[i].id); 
        }
      }
    });
      }

  void initMarker(request, requestId) {
    
    var markerIdVal = requestId;
    final MarkerId markerId = MarkerId(markerIdVal);
    //creating new markers
    final Marker marker = Marker(
      markerId: markerId,
      position:
          LatLng(request['location'].latitude, request['location'].longitude),
      infoWindow:
          InfoWindow(title: request['name'], snippet: request['description']),
      onTap: () => print('Test'),
    );
    setState(() {
      markers[markerId] = marker;
      //print(markerId);
    });
  }

Widget loadMap() {
    return GoogleMap(
      
      markers: Set<Marker>.of(markers.values),
      mapType: MapType.normal,
      initialCameraPosition:
          CameraPosition(target: LatLng(43.8031287, 20.453008), zoom: 12.0),
      onMapCreated: onMapCreated,

      // },
    );
  }

and in the buider, I just call loadMap() function as the body. As I mentioned, this works fine, but I would like to use Stream Builder for these functions to update in real time. Any ideas how to do it?

This thread has a similar issue, but I feel it’s not the best way to do it:

Flutter – Provide Real-Time Updates to Google Maps Using StreamBuilder

Here is the full code in case someone wants to test it out:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class MapScreen extends StatefulWidget {
  @override
  _MapScreenState createState() => _MapScreenState();
}
class _MapScreenState extends State<MapScreen> {
  Map<MarkerId, Marker> markers = <MarkerId, Marker>{}; //--> google
  GoogleMapController _controller;
  
   @override
  void initState() {
    populateMarkers();
    super.initState();
  }
  
   onMapCreated(GoogleMapController controller) async {
    _controller = controller;
    String value = await DefaultAssetBundle.of(context)
        .loadString('assets/map_style.json');
    _controller.setMapStyle(value);
  }

  populateMarkers() {
    FirebaseFirestore.instance.collection('marker').get().then((documents) {
      if (documents.docs.isNotEmpty) {
        for (int i = 0; i < documents.docs.length; i++) {
          initMarker(
              documents.docs[i].data(), documents.docs[i].id); //maybe error
          //documents.docs[i].data, documents.docs[i].id
        }
      }
    });
  }
  
   void initMarker(request, requestId) {
   
    var markerIdVal = requestId;
    final MarkerId markerId = MarkerId(markerIdVal);
    //creating new markers
    final Marker marker = Marker(
      markerId: markerId,
      position:
          LatLng(request['location'].latitude, request['location'].longitude),
      infoWindow:
          InfoWindow(title: request['name'], snippet: request['description']),
      onTap: () => print('Test'),
    );
    setState(() {
      markers[markerId] = marker;
      //print(markerId);
    });
  }

  Widget loadMap() {
    return GoogleMap(
      // markers: markers.values.toSet(),
      markers: Set<Marker>.of(markers.values),
      mapType: MapType.normal,
      initialCameraPosition:
          CameraPosition(target: LatLng(44.8031267, 20.432008), zoom: 12.0),
      onMapCreated: onMapCreated,
      cameraTargetBounds: CameraTargetBounds(LatLngBounds(
          northeast: LatLng(44.8927468, 20.5509553),
          southwest: LatLng(44.7465138, 20.2757283))),
      mapToolbarEnabled: false,
      //  onMapCreated: (GoogleMapController controller) {
      //   _controller = controller;
      // },
    );
  }
  
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

//-----------------------------------
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('App'),
        centerTitle: true,
        backgroundColor: Colors.blue[700],
        actions: [
          // ElevatedButton(
          //   onPressed: () => refresh(),
          //   child: Text('REFRESH'),
          // )
        ],
      ),
      body: loadMap(),
        );
  }
}


Get this bounty!!!