skip to Main Content

in my application I would like to write some information during the navigation into an external repository using RESTAPI call.
I have created a page stateful widget with a FutureBuilder to include where needed, I will pass parameters to this widget time by time.
I use already this external repository and I have created an apiserver to retrieve and write data.
I do not have any error nowhere BUT the widget does not do anything, it looks like it is not called at all.
In the code I print only for debug.

Any suggestion?
There is another simple way to achieve the same result?

I call it from the other pages in this way:
const insertLog("TestData");
Do not worry about the content of the data, it is a test for the moment.

Thanks in advance

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:myproject/src/constants/global.dart';
import 'package:myproject/src/models/db_model.dart';


// Insert Log

Future<Logs> writeLog(String plate) async {
  final response = await http.post(
    Uri.parse('https://js"${plServer}/api/log'),
    headers: <String, String>{
      'Content-Type': 'application/json'
    },
    body: jsonEncode(<String, String>{
      'date': plate,
      'plate': plate,
      'userid': plate,
      'activity': plate,    }),
  );

  if (response.statusCode == 201) {
    return Logs.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    throw Exception('Failed to insert log.');
  }
}

class insertLog extends StatefulWidget {
  const insertLog(this.plate);
  final String plate;

  @override
  State<insertLog> createState() => _insertLogState();
}

class _insertLogState extends State<insertLog> {
  late Future<Logs> log;


  @override
  void initState() {
    super.initState();
    print("Plate write log =" + widget.plate);
    log = writeLog(widget.plate);
  }

  String datetime = "";
  String plate = "";
  String userid = "";
  String activity = "";

  Map data = {"datetime": "","plate": "", "userid": "", "activity": ""};

  @override
  Widget build(BuildContext context) {
    print("Plate write log =" + widget.plate);
    return  const CircularProgressIndicator();

  }
}

2

Answers


  1. Chosen as BEST ANSWER

    The solution is quite easy ... just include this page and call the void inside the code using restApiLog("mytext");

    import 'dart:async';
    import 'dart:convert';
    
    import 'package:http/http.dart' as http;
    import 'package:passionelease/src/constants/global.dart';
    import 'package:passionelease/src/models/faq_model.dart';
    
    // Insert Log
    
    Future<Logs> writeLog(String plate) async {
      final response = await http.post(
        Uri.parse('${plServer}/api/log'),
        headers: <String, String>{
          'Content-Type': 'application/json'
        },
        body: jsonEncode(<String, String>{
    //      'datetime': DateTime.now().toString().substring(0,19),
          // 'date': plate,
          'plate': plate,
          'userid': plate,
          'activity': plate,    }),
      );
      
      if (response.statusCode == 200) {
        print('Posted your data: $plate');  // Added print statement
        return Logs.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
      } else {
        throw Exception('Failed to insert log.');
      }
    }
    
    void restApiLog(String plate) {
        print("Plate write log = ${plate}");
        writeLog(plate);
    }
    

  2. Try like this:

    import 'dart:async';
    import 'dart:convert';
    
    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    import 'package:myproject/src/constants/global.dart';
    import 'package:myproject/src/models/db_model.dart';
    
    Future<Logs> writeLog(String plate) async {
      final response = await http.post(
        Uri.parse('https://${plServer}/api/log'),  // Fixed the URL
        headers: <String, String>{
          'Content-Type': 'application/json',
        },
        body: jsonEncode(<String, String>{
          'date': DateTime.now().toString(),  // Updated to include the current date and time
          'plate': plate,
          'userid': 'your_user_id',  // Replace with the actual user ID
          'activity': 'your_activity',  // Replace with the actual activity
        }),
      );
    
      if (response.statusCode == 201) {
        print('Posted your data: $plate');  // Added print statement
        return Logs.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
      } else {
        throw Exception('Failed to insert log.');
      }
    }
    
    class InsertLog extends StatefulWidget {
      const InsertLog(this.plate);
      final String plate;
    
      @override
      State<InsertLog> createState() => _InsertLogState();
    }
    
    class _InsertLogState extends State<InsertLog> {
      late Future<Logs> log;
    
      @override
      void initState() {
        super.initState();
        print("Plate write log = ${widget.plate}");
        log = writeLog(widget.plate);
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Insert Log'),
          ),
          body: FutureBuilder<Logs>(
            future: log,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return Center(
                  child: CircularProgressIndicator(),
                );
              } else if (snapshot.hasError) {
                return Center(
                  child: Text('Error: ${snapshot.error}'),
                );
              } else {
                return Center(
                  child: Text('Log inserted successfully!'),
                );
              }
            },
          ),
        );
      }
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search